更新到新版本,报错。老版本的函数发现少了很多。把少的文件添加到目录中,发现可以用了。
?
using System.Diagnostics;
using System.Text;
using ZXing;
using ZXing.Common;
using ZXing.Multi.QrCode;
namespace WinFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 生成二维码图片
/// </summary>
/// <param name="strMessage">要生成二维码的字符串</param>
/// <param name="width">二维码图片宽度</param>
/// <param name="height">二维码图片高度</param>
/// <returns></returns>
private Bitmap? GetQRCodeByZXingNet(String strMessage, Int32 width, Int32 height)
{
Bitmap? result = null;
try
{
var barCodeWriter = new BarcodeWriter();
barCodeWriter.Format = BarcodeFormat.QR_CODE;
barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
barCodeWriter.Options.Height = height;
barCodeWriter.Options.Width = width;
barCodeWriter.Options.Margin = 0;
var bm = barCodeWriter.Encode(strMessage);
result = barCodeWriter.Write(bm);
}
catch (Exception ex)
{
return null;
}
return result;
}
/// <summary>
/// 解码二维码
/// </summary>
/// <param name="barcodeBitmap">待解码的二维码图片</param>
/// <returns>扫码结果</returns>
private Result DecodeQrCode(Bitmap barcodeBitmap)
{
var reader = new BarcodeReader();
reader.Options.CharacterSet = "UTF-8";
var result = reader.Decode(barcodeBitmap);
return null??result;
}
/// <summary>
/// 解码多个二维码
/// </summary>
/// <param name="bitmap">待解码的多个二维码图片</param>
/// <returns>扫码结果</returns>
private Result[] DecodeQRMulti(Bitmap bitmap)
{
var qc = new QRCodeMultiReader();
LuminanceSource source = new BitmapLuminanceSource(bitmap);
BinaryBitmap binarybitmap = new BinaryBitmap(new HybridBinarizer(source));
IDictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.Add(DecodeHintType.TRY_HARDER, "3");
Result[] rr = qc.decodeMultiple(binarybitmap, hints);
return null??rr ;
}
private void button1_Click(object sender, EventArgs e)
{
Bitmap bitmap = (Bitmap)Image.FromFile(Environment.CurrentDirectory + "\\" + "dm.bmp");
pictureBox1.Image = bitmap;
var re = DecodeQRMulti(bitmap);
if (re == null) { return; }
StringBuilder sb = new StringBuilder();
foreach (var i in re)
{
sb.Append(i.Text + i.ResultPoints[0] + i.ResultPoints[1] + i.ResultPoints[2] + "\r\n");
}
// string bb = stopwatch.ElapsedMilliseconds.ToString();//3ms
MessageBox.Show(sb.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bitmap = (Bitmap)Image.FromFile(Environment.CurrentDirectory + "\\" + "dm2.bmp");
pictureBox1.Image = bitmap;
var re = DecodeQrCode(bitmap);
if (re == null) { return; }
MessageBox.Show(re.Text+re.ResultPoints[0]+ re.ResultPoints[1]+ re.ResultPoints[2]);
}
private void button3_Click(object sender, EventArgs e)
{
var img= GetQRCodeByZXingNet("1234",200,200);
pictureBox1.Image = img;
}
}
}
生成二维码,读取二维码,读取多个二维码。
源码下载:
zxing.net最新版生成二维码,读取二维码,读取多个二维码。-C#文档类资源-CSDN文库
|