.NET 使用ZXing.NET 生成条形码,生成二维码,生成中间带图片的二维码
根据转载文章稍作整理,主要用了生成带logo的二维码图片。原路径:http://www.cnblogs.com/Interkey/p/qrcode.html
基于开源的 ZXing.NET 组件,代码如下:
先添加对ZXing.NET的引用,然后添加相应的命名空间:
using System; using System.Collections.Generic; using System.Drawing; using ZXing; using ZXing.Common; using ZXing.QrCode; using ZXing.QrCode.Internal;
方法一是生成二维码图片:
/// <summary> /// 生成二维码图片 /// </summary> /// <param name="contents">要生成二维码包含的信息</param> /// <param name="width">生成的二维码宽度(默认300像素)</param> /// <param name="height">生成的二维码高度(默认300像素)</param> /// <returns>二维码图片</returns> public static Bitmap GeneratorQrImage(string contents, int width = 300, int height = 300) { if (string.IsNullOrEmpty(contents)) { return null; } //本文地址:http://www.cnblogs.com/Interkey/p/qrcode.html EncodingOptions options = null; BarcodeWriter writer = null; options = new QrCodeEncodingOptions { DisableECI = true, CharacterSet = "UTF-8", Width = width, Height = height, ErrorCorrection = ErrorCorrectionLevel.H, }; writer = new BarcodeWriter(); writer.Format = BarcodeFormat.QR_CODE; writer.Options = options; Bitmap bitmap = writer.Write(contents); return bitmap; }
方法二是生成中间带图片的二维码图片:
/// <summary>
/// 生成中间带有图片的二维码图片
/// </summary>
/// <param name="contents">要生成二维码包含的信息</param>
/// <param name="middleImg">要生成到二维码中间的图片</param>
/// <param name="imageName">要生成到二维码图片的名字</param>
/// <param name="width">生成的二维码宽度(默认300像素)</param>
/// <param name="height">生成的二维码高度(默认300像素)</param>
/// <returns>中间带有图片的二维码</returns>
public static void GeneratorQrImage(string contents, Image middleImg, string imageName, int width = 300, int height = 300)
{
//if (string.IsNullOrEmpty(contents))
//{
// return null;
//}
//if (middleImg == null)
//{
// //return null;
// return GeneratorQrImage(contents);
//}
//构造二维码写码器
MultiFormatWriter mutiWriter = new MultiFormatWriter();
Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//生成二维码
BitMatrix bm = mutiWriter.encode(contents, BarcodeFormat.QR_CODE, width, height, hint);
BarcodeWriter barcodeWriter = new BarcodeWriter();
Bitmap bitmap = barcodeWriter.Write(bm);
//获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
int[] rectangle = bm.getEnclosingRectangle();
//计算插入图片的大小和位置
int middleImgW = Math.Min((int)(rectangle[2] / 3.5), middleImg.Width);
int middleImgH = Math.Min((int)(rectangle[3] / 3.5), middleImg.Height);
int middleImgL = (bitmap.Width - middleImgW) / 2;
int middleImgT = (bitmap.Height - middleImgH) / 2;
//将img转换成bmp格式,否则后面无法创建 Graphics对象
Bitmap bmpimg = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmpimg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(bitmap, 0, 0);
}
//在二维码中插入图片
Graphics myGraphic = Graphics.FromImage(bmpimg);
//白底
myGraphic.FillRectangle(Brushes.White, middleImgL, middleImgT, middleImgW, middleImgH);
myGraphic.DrawImage(middleImg, middleImgL, middleImgT, middleImgW, middleImgH);
//保存本地
var savePath = @"C:\Users\ThinkPadP50\Desktop\erweima\" + imageName;
bmpimg.Save(savePath);
//return bmpimg;
}
/// <summary>
/// 生成二维码图片
/// </summary>
/// <param name="contents">要生成二维码包含的信息</param>
/// <param name="width">生成的二维码宽度(默认300像素)</param>
/// <param name="height">生成的二维码高度(默认300像素)</param>
/// <returns>二维码图片</returns>
public static Bitmap GeneratorQrImage(string contents, int width = 300, int height = 300)
{
if (string.IsNullOrEmpty(contents))
{
return null;
}
EncodingOptions options = null;
BarcodeWriter writer = null;
options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = width,
Height = height,
ErrorCorrection = ErrorCorrectionLevel.H,
};
writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;
Bitmap bitmap = writer.Write(contents);
return bitmap;
}
二维码解析:
//解析二维码
// create a barcode reader instance
public static ReaderInstance GetReaderInstance(string imageName)
{
IBarcodeReader reader = new BarcodeReader();
// load a bitmap
var path = @"C:\Users\ThinkPadP50\Desktop\erweima\"+ imageName;
Bitmap barcodeBitmap = (Bitmap)Image.FromFile(path);
// detect and decode the barcode inside the bitmap
Result result = reader.Decode(barcodeBitmap);
// do something with the result
if (result != null)
{
return new ReaderInstance
{
txtDecoderType = result.BarcodeFormat.ToString(),
txtDecoderContent = result.Text
};
}
return null;
}
}
public class ReaderInstance
{
public string txtDecoderType { get; set; }
public string txtDecoderContent { get; set; }
}
主函数代码:
static class Program
{
static void Main(string[] args)
{
/// <summary>
/// 生成中间带有图片的二维码图片
/// </summary>
/// <param name="contents">要生成二维码包含的信息</param>
/// <param name="middleImg">要生成到二维码中间的图片</param>
/// <param name="imageName">要生成到二维码图片的名字</param>
/// <param name="width">生成的二维码宽度(默认300像素)</param>
/// <param name="height">生成的二维码高度(默认300像素)</param>
/// <returns>中间带有图片的二维码</returns>
//Image logo = Image.FromFile(@"C:\Users\ThinkPadP50\Desktop\erweima\me.png");
//ErWeiMa.GeneratorQrImage("123456789",logo,"456.png");
//Console.WriteLine("OK");
//Console.Read();
//二维码解析
var imageName = "logo.png";
var result= ErWeiMa.GetReaderInstance(imageName);
Console.WriteLine("二维码类型:"+result.txtDecoderType+";二维码内容:"+result.txtDecoderContent);
Console.Read();
}
}
中间有图片与没有图片的生成的不一样,原因不清楚,初步以为中间有图片的是因为容错率的原故。
QR码的数据编码方式有四种:
数字(Numeric):0-9
大写字母和数字(alphanumeric):0-9,A-Z,空格,$,%,*,+,-,.,/,:
二进制/字节:通过 ISO/IEC 8859-1 标准编码
日本汉字/假名:通过 Shift JISJIS X 0208 标准编码
QR码四种容错级别
L(Low):约可纠错7%的数据码字
M(Medium):约可纠错15%的数据码字
Q(Quartile):约可纠错25%的数据码字
H(High):约可纠错30%的数据码字(带logo图片的容错级别选择H)
其他常用可生成二维码的组件有:QrCode.Net(开源)、ZXing(开源)、ThoughtWorks.QRCode等。
了解了二维码的数据存储后,可以基于这些技术生成富有创意的二维码。
附加一个生成条形码的代码:
static void Generate2(string text)
{
BarcodeWriter writer = new BarcodeWriter();
//使用ITF 格式,不能被现在常用的支付宝、微信扫出来
//如果想生成可识别的可以使用 CODE_128 格式
//writer.Format = BarcodeFormat.ITF;
writer.Format = BarcodeFormat.CODE_128;
EncodingOptions options = new EncodingOptions()
{
Width = 150,
Height = 50,
Margin = 2
};
writer.Options = options;
Bitmap map = writer.Write(text);
string filename = @"C:\Users\ThinkPadP50\Desktop\erweima\generate2.png";
map.Save(filename, ImageFormat.Png);
}