C#實現(xiàn)條形碼識別的解決方案分享
簡介
主流的識別庫主要有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環(huán)境下也能正常使用,正常情況下輸出目錄會自動生成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年,后面的版本只是將庫做了個標準版,按自己的需求選擇版本:
- ThoughtWorks.QRCode:原始版本,最后更新時間2015年。
- ThoughtWorks.QRCode.Standard(推薦使用):netstandard2.0版本,修復bug,增加了自動QRCodeVersion功能。
- ThoughtWorks.QRCode.Core:netstandard2.0版本,功能未修復變更。
識別庫使用方法參考:C#使用zxing,zbar,thoughtworkQRcode解析二維碼。
擴展:開源掃碼軟件
推薦一個C# WPF 原生開發(fā)的在電腦上識別條碼的工具軟件QrCodeScanner,功能如下:
支持四種模式:截圖識別 + 攝像頭識別 + 本地圖片識別 + 作為掃描槍使用
支持Zbar和Zxing兩種主流引擎
支持多碼同掃
支持Material Design繽紛主題色與暗黑模式
獨創(chuàng)的掃描槍模
到此這篇關于C#實現(xiàn)條形碼識別的解決方案分享的文章就介紹到這了,更多相關C#條形碼識別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#中Trim()、TrimStart()、TrimEnd()的用法介紹
這篇文章主要介紹了C#中Trim()、TrimStart()、TrimEnd()的用法,有需要的朋友可以參考一下2014-01-01C#/C++ 通過ODBC連接OceanBase Oracle租戶的詳細過程
近期我們項目正處于將Oracle數據庫遷移到OceanBase Oracle租戶模式的階段,考慮到我們項目采用了C++和C#混合開發(fā),并且使用了多種技術,因此存在多種數據庫連接方式,C#連接OceanBase的案例相對較少,因此我特意記錄下這一過程,感興趣的朋友一起看看吧2024-05-05