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; } }
桂棹兮兰桨,击空明兮溯流光。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!