ToB企服应用市场:ToB评测及商务社交产业平台

标题: C#条码识别的解决方案(ZBar) [打印本页]

作者: 商道如狼道    时间: 2023-7-24 01:48
标题: C#条码识别的解决方案(ZBar)
简介

主流的识别库主要有ZXing.NET和ZBar,OpenCV 4.0后加入了QR码检测和解码功能。本文使用的是ZBar,同等条件下ZBar识别率更高,图片和部分代码参考在C#中使用ZBar识别条形码
使用ZBar

通过NuGet安装ZBar,必须使用1.0.0版本,最新的1.0.2版本无法自动生成相关的dll并且使用不了1.0.0版的dll。
库默认支持netcoreapp3.1,在.NET6环境下也能正常使用,正常情况下输出目录会自动生成lib文件夹和dll文件
注:ZBar 1.0.0在x86平台下可正常运行,但Debug会报错,建议使用x64或AnyCPU。
条码识别:
  1. /// <summary>
  2. /// 条码识别
  3. /// </summary>
  4. static List<ZBar.Symbol> ScanBarCode(string filename)
  5. {
  6.     var bitmap = (Bitmap)Image.FromFile(filename);
  7.     bitmap = MakeGrayscale3(bitmap);
  8.     List<ZBar.Symbol> result = new List<ZBar.Symbol>();
  9.     using (var scanner = new ZBar.ImageScanner())
  10.     {
  11.         var symbols = scanner.Scan(bitmap);
  12.         if (symbols != null && symbols.Count > 0)
  13.         {
  14.             result.AddRange(symbols);
  15.         }
  16.     }
  17.     return result;
  18. }
  19. /// <summary>
  20. /// 处理图片灰度
  21. /// </summary>
  22. static Bitmap MakeGrayscale3(Bitmap original)
  23. {
  24.     //create a blank bitmap the same size as original
  25.     Bitmap newBitmap = new Bitmap(original.Width, original.Height);
  26.     //get a graphics object from the new image
  27.     Graphics g = Graphics.FromImage(newBitmap);
  28.     //create the grayscale ColorMatrix
  29.     System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(
  30.         new float[][]
  31.         {
  32.             new float[] {.3f, .3f, .3f, 0, 0},
  33.             new float[] {.59f, .59f, .59f, 0, 0},
  34.             new float[] {.11f, .11f, .11f, 0, 0},
  35.             new float[] {0, 0, 0, 1, 0},
  36.             new float[] {0, 0, 0, 0, 1}
  37.       });
  38.     //create some image attributes
  39.     ImageAttributes attributes = new ImageAttributes();
  40.     //set the color matrix attribute
  41.     attributes.SetColorMatrix(colorMatrix);
  42.     //draw the original image on the new image
  43.     //using the grayscale color matrix
  44.     g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
  45.        0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
  46.     //dispose the Graphics object
  47.     g.Dispose();
  48.     return newBitmap;
  49. }
复制代码
使用方法:
  1. Console.WriteLine(ZBar.ZBar.Version);
  2. var symbols = ScanBarCode("426301-20160127111209879-611759974.jpg");
  3. string result = string.Empty;
  4. symbols.ForEach(s => Console.WriteLine($"条码类型:{s.Type} 条码内容:{s.Data} 条码质量:{s.Quality}"));
  5. Console.ReadKey();
复制代码
扩展:其它条码识别库

在C#平台下还有一个ThoughtWorks.QRCode库也支持条码解析,具体效果还没有测试。原始代码最后的版本是在2015年,后面的版本只是将库做了个标准版,按自己的需求选择版本:
识别库使用方法参考:C#使用zxing,zbar,thoughtworkQRcode解析二维码,附源代码
扩展:开源扫码软件

推荐一个C# WPF 原生开发的在电脑上识别条码的工具软件QrCodeScanner,功能如下:
附件


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4