微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

条码识别:

/// <summary>
/// 条码识别
/// </summary>
static List<ZBar.Symbol> ScanBarCode(string filename)
{
    var bitmap = (Bitmap)Image.FromFile(filename);
    bitmap = MakeGrayscale3(bitmap);
    List<ZBar.Symbol> result = new List<ZBar.Symbol>();
    using (var scanner = new ZBar.ImageScanner())
    {
        var symbols = scanner.Scan(bitmap);
        if (symbols != null && symbols.Count > 0)
        {
            result.AddRange(symbols);
        }
    }
    return result;
}

/// <summary>
/// 处理图片灰度
/// </summary>
static Bitmap MakeGrayscale3(Bitmap original)
{
    //create a blank bitmap the same size as original
    Bitmap newBitmap = new Bitmap(original.Width, original.Height);

    //get a graphics object from the new image
    Graphics g = Graphics.FromImage(newBitmap);

    //create the grayscale ColorMatrix
    System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(
        new float[][]
        {
            new float[] {.3f, .3f, .3f, 0, 0},
            new float[] {.59f, .59f, .59f, 0, 0},
            new float[] {.11f, .11f, .11f, 0, 0},
            new float[] {0, 0, 0, 1, 0},
            new float[] {0, 0, 0, 0, 1}
      });

    //create some image attributes
    ImageAttributes attributes = new ImageAttributes();
    //set the color matrix attribute
    attributes.SetColorMatrix(colorMatrix);
    //draw the original image on the new image
    //using the grayscale color matrix
    g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
       0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

    //dispose the Graphics object
    g.dispose();
    return newBitmap;
}

使用方法

Console.WriteLine(ZBar.ZBar.Version);
var symbols = ScanBarCode("426301-20160127111209879-611759974.jpg");
string result = string.Empty;
symbols.ForEach(s => Console.WriteLine($"条码类型:{s.Type} 条码内容:{s.Data} 条码质量:{s.Quality}"));
Console.ReadKey();

扩展:其它条码识别库

在C#平台下还有一个ThoughtWorks.QRCode库也支持条码解析,具体效果还没有测试。原始代码最后的版本是在2015年,后面的版本只是将库做了个标准版,按自己的需求选择版本:

识别库使用方法参考:C#使用zxing,zbar,thoughtworkQRcode解析二维码,附源代码

扩展:开源扫码软件

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

附件

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐