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);
}
}
1条答案
按热度按时间5lhxktic1#
请尝试以下代码。它已经过测试,但你可能需要调整它以适应你的使用,这应该不会太困难。
下载/安装NuGet包:
ZXing.Net
(版本:0.16.8)增加以下using指令:
using System.IO;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;
编码:
二维码解码(用法一):
二维码解码(用法二):
注意:下面的代码中,QR码是从文件中读取的,并放置在
byte[]
中。从文件阅读是为了演示/测试目的。保存二维码(用法一):
保存二维码(用法二):
注意:下面代码中,二维码保存到
byte[]
,然后写入文件。写入文件用于演示/测试目的。资源