.net core使用ZXing.Net识别图片中的二维码或条型码
.net core 3.1 识别图片中的二维码或条型码
安装扩展ZXing.Net.Bindings.ZKWeb.System.Drawing
命名空间:
using System; using System.IO; using System.DrawingCore; using ZXing.Common; using ZXing; using ZXing.QrCode; using ZXing.ZKWeb; using System.Net; using System.Threading; using System.DrawingCore.Imaging;
public static class CodeHelper { /// <summary> /// 读取二维码或者条形码(通过http路径) /// </summary> /// <param name="url">http路径</param> /// <returns>returns</returns> public static string ReadFromImage(string url) { var tryCount = 1; Console.WriteLine($"正在识别:url={url}"); while (tryCount <= 3) {// 偶尔识别不出时重试 try { if (string.IsNullOrWhiteSpace(url)) { return ""; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; using (WebResponse response = request.GetResponse()) { using (var stream = response.GetResponseStream()) { using (var image = Image.FromStream(stream)) { using (Bitmap bmp = Resizer(image, 2000)) {// 因有些图片较模糊,故放大比较容易识别。可不放大 Bitmap bmp = new Bitmap(image); // 该类名称为BarcodeReader,可以读二维码和条形码 var zzb = new ZXing.ZKWeb.BarcodeReader(); zzb.Options = new DecodingOptions { CharacterSet = "UTF-8" }; Result r = zzb.Decode(bmp); string resultText = null; if (r != null) { resultText = r.Text; } if (!string.IsNullOrWhiteSpace(resultText)) { Console.WriteLine($"识别结果:{resultText}"); } tryCount = 10; return resultText; } } } } } catch (Exception ex) { Console.WriteLine($"ReadFromImage异常,url={url},异常消息:{ex.Message}\r\n"); tryCount++; if (tryCount <= 3) { Console.WriteLine($"0.5秒后将重试"); Thread.Sleep(500); } } } return ""; } /// <summary> /// 按宽度放大 /// </summary> /// <param name="bmp">bmp</param> /// <param name="width">width</param> /// <returns>returns</returns> private static Bitmap Resizer(this Image bmp, int width) { if (bmp.Width >= width) { return new Bitmap(bmp); } Bitmap ob = new Bitmap(width, bmp.Height * width / bmp.Width); using (var g = Graphics.FromImage(ob)) { g.Clear(Color.WhiteSmoke); g.DrawImage(bmp, new Rectangle(0, 0, ob.Width, ob.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel); } return ob; } /// <summary> /// 读取二维码或者条形码(通过物理路径) /// </summary> /// <param name="imgFile">物理路径</param> /// <returns>returns</returns> public static string ReadFromImage2(string imgFile) { if (string.IsNullOrWhiteSpace(imgFile)) { return ""; } Image img = Image.FromFile(imgFile); Bitmap b = new Bitmap(img); // 该类名称为BarcodeReader,可以读二维码和条形码 var zzb = new ZXing.ZKWeb.BarcodeReader(); zzb.Options = new DecodingOptions { CharacterSet = "UTF-8" }; Result r = zzb.Decode(b); string resultText = null; if (r != null) { resultText = r.Text; } b.Dispose(); img.Dispose(); return resultText; } }