生成qr码图像

时间:2016-01-04 08:16:30

标签: c# winforms barcode

使用下面这行代码后

 private void button1_Click(object sender, EventArgs e)
    {
        string barcode = textBox1.Text;
        Bitmap bitmap = new Bitmap(barcode.Length * 40, 150);

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            Font oFont = new System.Drawing.Font("IDAutomationHC39M", 20);
            PointF point = new PointF(2f, 2f);
            SolidBrush white = new SolidBrush(Color.White);
            SolidBrush black = new SolidBrush(Color.Black);
            graphics.FillRectangle(white,0,0,bitmap.Width,bitmap.Height);
            graphics.DrawString("*" + barcode + "*", oFont, black, point);
        }
        using (MemoryStream ms = new MemoryStream())
        {
            bitmap.Save(ms,ImageFormat.Png);
            pictureBox1.Image = bitmap;
            pictureBox1.Height = bitmap.Height;
            pictureBox1.Width = bitmap.Width;
        }
    }

我能够生成此输出图像条形码

enter image description here

我想生成一个条形码输出,如下图所示,我该如何实现这个

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以这样做

private System.Drawing.Image GenerateQRCode(string content, int size)
{
    QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.H);
    QrCode qrCode;
    encoder.TryEncode(content, out qrCode);

    GraphicsRenderer gRenderer = new GraphicsRenderer(new FixedModuleSize(4, QuietZoneModules.Two), System.Drawing.Brushes.Black, System.Drawing.Brushes.White);
    //Graphics g = gRenderer.Draw(qrCode.Matrix);

    MemoryStream ms = new MemoryStream();
    gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Bmp, ms);

    var imageTemp = new Bitmap(ms);

    var image = new Bitmap(imageTemp, new System.Drawing.Size(new System.Drawing.Point(size, size)));

    //image.Save("file.bmp", ImageFormat.Bmp);

    return (System.Drawing.Image)image;
}

Implementaion

string barcode = textBox1.Text; 
codeImage = GenerateQRCode(barcode, 120);
// you can make a smaller image as per your need
rect = new System.Drawing.Rectangle(1080, 530, codeImage.Width, codeImage.Height);
using (Graphics g = Graphics.FromImage(picEdit))
{
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    g.DrawImage(codeImage, rect);
}   

不要忘记添加

using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;

来自GitHub: QrCode.Net