将自定义图像或文本添加到ZXing.Net生成的QR码中

时间:2015-06-25 14:58:33

标签: c# zxing qr-code

我使用ZXing.Net库生成QR码图片 -

app screenshot

在班上名列前茅:

$
  Project
    Main
      Project
    Branch
      Branch1
      Branch2
    Private
      Smith, John
        my-personal-branch
      Doe, John
        huge-refactoring

我的方法:

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);

请告诉我如何在QR码中间添加短文字字符串或自定义图片 - 类似于下面的Wikipedia visual QR code

Wikipedia

更新:

在QR代码中嵌入自定义徽标(不破坏后者!)似乎不是一项微不足道的任务,因为科学出版物QR Images: Optimized Image Embedding in QR Codes显示......

但我仍然想知道是否可以生成QR码(如上面的源代码所示),然后用自定义文本或徽标覆盖它,然后再通过ZXing.Net验证生成的图像。

2 个答案:

答案 0 :(得分:11)

Here we go (you can use any logo):

using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode.Internal;
using ZXing.Rendering;


namespace Test
{
    public partial class Form1 : Form
{

    private string imagePath = @"YourPath";
    private string url = @"https://en.WIKIPEDIA.ORG/";
    private int size = 400;
    public Form1()
    {
        InitializeComponent();

        pictureBox1.Image = GenerateQR(size, size, url);
        pictureBox1.Height = size;
        pictureBox1.Width = size;
        Console.WriteLine(checkQR(new Bitmap(pictureBox1.Image)));
    }

    public bool checkQR(Bitmap QrCode)
    {
        var reader = new BarcodeReader();
        var result = reader.Decode(QrCode);
        if (result == null)
            return false;
        return result.Text == url;
    }


    public Bitmap GenerateQR(int width, int height, string text)
    {
        var bw = new ZXing.BarcodeWriter();

        var encOptions = new ZXing.Common.EncodingOptions
        {
            Width = width,
            Height = height,
            Margin = 0,
            PureBarcode = false
        };

        encOptions.Hints.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        bw.Renderer = new BitmapRenderer();
        bw.Options = encOptions;
        bw.Format = ZXing.BarcodeFormat.QR_CODE;
        Bitmap bm = bw.Write(text);
        Bitmap overlay = new Bitmap(imagePath);

        int deltaHeigth = bm.Height - overlay.Height;
        int deltaWidth = bm.Width - overlay.Width;

        Graphics g = Graphics.FromImage(bm);
        g.DrawImage(overlay, new Point(deltaWidth/2,deltaHeigth/2));

        return bm;
    }

}

The result:

enter image description here

And the output:

True

答案 1 :(得分:2)

由于你从ZXing获得了一个位图,你可以使用标准的C#技术来绘制文本。有关详细信息,请参阅此答案:

c# write text on bitmap

对于后人来说,这是一些无耻复制的代码:

Bitmap bmp = //from ZXing;

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();