C# 生成和识别二维码


本来认为这功能在网上一搜一大堆,结果确实如此。但没有一个能用的,给一个微信一码通二维码,全都识别不了。

要么就是要收费,收个毛线,这东西都要收费,以后程序员写个软件岂不还没写就亏本了。

于是乎一顿搜索,经测试代码稳定,无论是纯二维码还是复杂图像嵌入二维码,均可识别。

第一步:Install-Package ZXing.Net -Version 0.16.6 

引入这个com组件

第二步,写代码:



class Program
{
static void Main(string[] args)
{
var data = "http://programmingnotes.org/";

// Encode data to a QR code byte array
var bytes = CreateQRCode(data);

//File.WriteAllBytes(@"c:\a.png", bytes);

Console.WriteLine($"Length: {bytes.Length}");

// Decode QR code to a string
var result = ReadQRCode(bytes);

var result2 = ReadQRCode(File.ReadAllBytes(@"E:\Desktop\erweima\微信图片_20210721150957.jpg"));

Console.WriteLine($"Result: {result}");
}

/// <summary>
/// Converts a string and encodes it to a QR code byte array
/// </summary>
/// <param name="data">The data to encode</param>
/// <param name="height">The height of the QR code</param>
/// <param name="width">The width of the QR code</param>
/// <param name="margin">The margin around the QR code</param>
/// <returns>The byte array of the data encoded into a QR code</returns>
public static byte[] CreateQRCode(string data, int height = 100
, int width = 100, int margin = 0)
{
byte[] bytes = null;
var barcodeWriter = new ZXing.BarcodeWriter()
{
Format = ZXing.BarcodeFormat.QR_CODE,
Options = new ZXing.QrCode.QrCodeEncodingOptions()
{
Height = height,
Width = width,
Margin = margin
}
};
using (var image = barcodeWriter.Write(data))
{
using (var stream = new System.IO.MemoryStream())
{
image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
bytes = stream.ToArray();
}
}
return bytes;
}

/// <summary>
/// Converts a QR code and decodes it to its string data
/// </summary>
/// <param name="bytes">The QR code byte array</param>
/// <returns>The string data decoded from the QR code</returns>
public static string ReadQRCode(byte[] bytes)
{
var result = string.Empty;
using (var stream = new System.IO.MemoryStream(bytes))
{
using (var image = System.Drawing.Image.FromStream(stream))
{
var barcodeReader = new ZXing.BarcodeReader();
var decoded = barcodeReader.Decode((System.Drawing.Bitmap)image);
if (decoded != null)
{
result = decoded.Text;
}
}
}
return result;
}
}



桂棹兮兰桨,击空明兮溯流光。