写在前面
这是ZXing.Net类库的系列文章,实现在二维码中间插入一个logo图标
C# 使用ZXing.Net生成二维码和条码-CSDN博客
C# 使用ZXing.Net识别二维码和条码-CSDN博客
代码实现
该段代码主体来自其他文章,贴在这做个记录
/// <summary>
/// 生成带Logo的二维码
/// </summary>
private void GenerateQrCodeWithLogo(string text)
{//Logo 图片var logo = new Bitmap(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"favicon32.ico"));//构造二维码写码器var writer = new MultiFormatWriter();var hint = new Dictionary<EncodeHintType, object>{{ EncodeHintType.CHARACTER_SET, "UTF-8" },{ EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H }};//生成二维码 var bm = writer.encode(text, BarcodeFormat.QR_CODE, 300, 300, hint);var barcodeWriter = new BarcodeWriter();var map = barcodeWriter.Write(bm);//获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)int[] rectangle = bm.getEnclosingRectangle();//计算插入图片的大小和位置int middleW = Math.Min((int)(rectangle[2] / 3.5), logo.Width);int middleH = Math.Min((int)(rectangle[3] / 3.5), logo.Height);int middleL = (map.Width - middleW) / 2;int middleT = (map.Height - middleH) / 2;//将img转换成bmp格式,否则后面无法创建Graphics对象var bmpimg = new Bitmap(map.Width, map.Height, 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(map, 0, 0);//将二维码插入图片var myGraphic = Graphics.FromImage(bmpimg);//填充白底myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH);//设置图片pictureBox1.Image = bmpimg;
}
调用示例
生成了带logo图标的二维码,识别也是正常的。