C# 使用ZXing.Net生成带Logo的二维码

发布时间:2023年12月31日

写在前面

这是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图标的二维码,识别也是正常的。

文章来源:https://blog.csdn.net/rjcql/article/details/135304995
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。