简体   繁体   English

用C#创建二维码并保存为图片

[英]Create QRCode with C# and save it as an image

I'm receiving data from a URL on our web application that's dynamically generated using an API's response.我正在从我们的 web 应用程序上的 URL 接收数据,这些数据是使用 API 响应动态生成的。 I have to handle it by putting it in a QRCode and send this QRCode back to the front-end for my client to download it.我必须通过将其放入QRCode并将此 QRCode 发送回前端以供我的客户端下载来处理它。 We're using C# for back-end and React.js for the front-end.我们在后端使用 C#,在前端使用 React.js。

I've tried to use ZXIng libraries for C# but with no success.我曾尝试将ZXIng库用于 C#,但没有成功。 I've tried a lot of code, but nothing seems to happen.我尝试了很多代码,但似乎什么也没发生。

Try the following code.试试下面的代码。 It's been tested, but you may need to adapt it for your usage which shouldn't be too difficult.它已经过测试,但您可能需要根据您的使用情况调整它,这应该不会太困难。

Download/install NuGet package: ZXing.Net下载/安装 NuGet package: ZXing.Net

Add the following using directives :添加以下使用指令

  • using System.IO;
  • using ZXing;
  • using ZXing.Common;
  • using ZXing.QrCode;

Code :代码

private Bitmap CreateQrCode(string data)
{
    //specify desired options
    QrCodeEncodingOptions options = new QrCodeEncodingOptions()
    {
        CharacterSet = "UTF-8",
        DisableECI = true,
        Width = 250,
        Height = 250
    };

    //create new instance and set properties
    BarcodeWriter writer = new BarcodeWriter()
    {
        Format = BarcodeFormat.QR_CODE,
        Options = options
    };

    //create QR code and return Bitmap
    return writer.Write(data);
}

private byte[] GetQrCodeBytes(string data, System.Drawing.Imaging.ImageFormat imgFormat)
{
    using (MemoryStream ms = new MemoryStream())
    {
        //create QR code and save to file
        using (Bitmap bmp = CreateQrCode(data))
        {
            //save to MemoryStream
            bmp.Save(ms, imgFormat);
        }

        return ms.ToArray();
    }
}

private string GetTextFromQrCode(byte[] qrcodeBytes)
{
    //specify desired options
    DecodingOptions options = new DecodingOptions()
    {
        CharacterSet = "UTF-8"
    };

    //create new instance and set properties
    BarcodeReader reader = new BarcodeReader() { Options = options };

    using (MemoryStream ms = new MemoryStream(qrcodeBytes))
    {
        using (Bitmap bmp = (Bitmap)Bitmap.FromStream(ms))
        {
            //decode QR code
            Result r = reader.Decode(bmp);

            //return QR code text
            return r.Text;
        }
    }
}

private string GetTextFromQrCode(string filename)
{
    //specify desired options
    DecodingOptions options = new DecodingOptions()
    {
        CharacterSet = "UTF-8"
    };

    //create new instance and set properties
    BarcodeReader reader = new BarcodeReader() { Options = options };

    //read image and convert to Bitmap
    using (Bitmap bmp = (Bitmap)Bitmap.FromFile(filename))
    {
        //decode QR code
        Result r = reader.Decode(bmp);

        //return QR code text
        return r.Text;
    }
}

private void SaveQrCode(string data, string filename, System.Drawing.Imaging.ImageFormat imgFormat)
{
    //create QR code and save to file
    using (Bitmap bmp = CreateQrCode(data))
    {
        bmp.Save(filename, imgFormat);
    }
}

Decode QR Code (Usage 1):解码 QR 码(用法 1):

string filename = @"C:\Temp\TestQrCode.png"
string qrcodeText = GetTextFromQrCode(filename);

Decode QR Code (Usage 2):解码 QR 码(用法 2):

Note : In the code below, the QR code is read from a file and placed in a byte[] .注意:在下面的代码中,QR 码是从文件中读取的,并放在byte[]中。 Reading from a file is for demonstration/testing purposes.从文件中读取是为了演示/测试目的。

string filename = @"C:\Temp\TestQrCode.png"
byte[] qrcodeBytes = File.ReadAllBytes(filename);
string qrcodeText = GetTextFromQrCode(qrcodeBytes);

Save QR Code (Usage 1):保存二维码(用法一):

string qrcodeText = "This is a test";
string filename = @"C:\Temp\TestQrCode.png"

//get filename extension
string ext = Path.GetExtension(filename);

if (ext == ".bmp" || ext == ".dib" || ext == ".rle")
    SaveQrCode(qrcodeText, filename, System.Drawing.Imaging.ImageFormat.Bmp);
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".jfif" || ext == ".jpe")
    SaveQrCode(qrcodeText, fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
else if (ext == ".png")
    SaveQrCode(qrcodeText, fileName, System.Drawing.Imaging.ImageFormat.Png);

Save QR Code (Usage 2):保存二维码(用法二):

Note : In the code below, the QR code is saved to a byte[] , then written to a file.注意:在下面的代码中,QR 码被保存到一个byte[]中,然后写入到一个文件中。 Writing to a file is for demonstration/testing purposes.写入文件用于演示/测试目的。

string qrcodeText = "This is a test";
string filename = @"C:\Temp\TestQrCode.png"

//get filename extension
string ext = Path.GetExtension(filename);

byte[] qrcodeBytes = null;

if (ext == ".bmp" || ext == ".dib" || ext == ".rle")
    qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Bmp);
else if (ext == ".jpg" || ext == ".jpeg" || ext == ".jfif" || ext == ".jpe")
    qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Jpeg);
else if (ext == ".png")
    qrcodeBytes = GetQrCodeBytes(qrcodeText, System.Drawing.Imaging.ImageFormat.Png);

//save to file
File.WriteAllBytes(fileName, qrcodeBytes);

Resources资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM