赞
踩
1、添加Nuget包,引用ZXing.Net
/// <summary> /// 生成二维码 /// </summary> /// <param name="filePath">地址</param> /// <param name="qrCodeContent">内容</param> public static void CreateZXingQrCode(string filePath, string qrCodeContent) { //设置规格 ZXing.QrCode.QrCodeEncodingOptions options = new ZXing.QrCode.QrCodeEncodingOptions() { Width = 500,//设置二维码的宽度 Height = 500,//设置二维码的高度 Margin = 1,//设置二维码的边距 CharacterSet = "UTF-8",//设置内容编码 DisableECI = true, }; //生成二维码 ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter() { Format = ZXing.BarcodeFormat.QR_CODE,//生成类型 Options = options,//设置格式 }; // System.Drawing.Bitmap bitmap = writer.Write(qrCodeContent);//存放二维码; //进行保存 bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); } /// <summary> /// 生成带logo的二维码 /// </summary> /// <param name="filePath"></param> /// <param name="qrCodeContent"></param> /// <param name="imagePath"></param> public static void CreateZXingQrCode(string filePath, string qrCodeContent, string imagePath) { //设置规格 ZXing.QrCode.QrCodeEncodingOptions option = new ZXing.QrCode.QrCodeEncodingOptions() { CharacterSet = "UTF-8",// 设置编码格式,否则读中文会乱码 Height = 200, Width = 200, Margin = 1,// 设置二维码周围空白边距(可选) }; //生成图片 ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter() { Options = option, Format = ZXing.BarcodeFormat.QR_CODE,//生成类型 }; System.Drawing.Bitmap img = writer.Write(qrCodeContent); // 添加logo图片 System.Drawing.Bitmap logoImg = System.Drawing.Bitmap.FromFile(imagePath) as System.Drawing.Bitmap; System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img); System.Drawing.Rectangle logoRec = new System.Drawing.Rectangle() ; //设置logo图片的大小和绘制位置 logoRec.Width = img.Width / 6; logoRec.Height = img.Height / 6; logoRec.X = img.Width / 2 - logoRec.Width / 2; // 中心点 logoRec.Y = img.Height / 2 - logoRec.Height / 2; graphics.DrawImage(logoImg, logoRec); //保存绘制后的图片 img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); img.Dispose(); } /// <summary> /// 读取二维码 /// </summary> /// <param name="filePath">地址</param> /// <returns></returns> public static string ReadZXingQrCode(string filePath) { //读取规格 ZXing.Common.DecodingOptions options = new ZXing.Common.DecodingOptions(); options.PossibleFormats = new List<ZXing.BarcodeFormat>() { ZXing.BarcodeFormat.QR_CODE }; ZXing.BarcodeReader br = new ZXing.BarcodeReader() { Options = options }; //指定规格 //读取图片 System.Drawing.Image image = System.Drawing.Image.FromFile(filePath); //读取图片内容 ZXing.Result rs = br.Decode(image as System.Drawing.Bitmap); return rs.Text; }
实现效果如下:
仅个人记录
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。