C#使用ZXing.Net實現(xiàn)識別二維碼和條碼
寫在前面
上一篇寫了 C# 使用ZXing.Net生成二維碼和條碼
使用ZXing.Net解碼非常簡單,事實上就只用一行代碼就好了,這么簡單那為什么還要貼在這里呢,原因是開始時,在網(wǎng)上看資料看到一篇文章,稀里嘩啦寫了一堆代碼,然后拿來運行一下,竟然還得不到預(yù)期的結(jié)果;看了下用了最復(fù)雜的方式,調(diào)用了參數(shù)最多的重載函數(shù),問題卻沒有解決,所以在網(wǎng)上查找資料,鑒別成本有時候是很高的;大部分的代碼拷來拷去,完全不做驗證,實在是浪費時間;最簡單有效的辦法還是盡量往信息的源頭去追溯,比如官網(wǎng)文檔、GitHub上的源碼介紹、業(yè)內(nèi)大牛的文章等。最好還是自己把代碼跑一遍,不僅可以確認也能加深印象,下次碰到同類問題或許拿來就用了,效率就是這么提升的。
代碼實現(xiàn)
var reader = new BarcodeReader(); var result = reader.Decode((Bitmap)pictureBox1.Image); if (result != null) { lblMessage.Text = result.Text; } else { lblMessage.Text = "None"; }
反面教材原代碼如下:
// create a barcode reader instance IBarcodeReader reader = new BarcodeReader(); // 加載圖片文件 Bitmap image = new Bitmap("D:\\PrideJoy\\Zxing.Demo\\Zxing.demo\\bin\\Debug\\net7.0\\qr-image.jpg"); // 獲取rawRGB數(shù)據(jù) Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); System.Drawing.Imaging.BitmapData bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = Math.Abs(bmpData.Stride) * image.Height; byte[] rawRGB = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rawRGB, 0, bytes); image.UnlockBits(bmpData); // 獲取格式(format) RGBLuminanceSource.BitmapFormat format; switch (image.PixelFormat) { case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: format = RGBLuminanceSource.BitmapFormat.Gray8; break; case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale: format = RGBLuminanceSource.BitmapFormat.Gray16; break; case System.Drawing.Imaging.PixelFormat.Format24bppRgb: format = RGBLuminanceSource.BitmapFormat.RGB24; break; case System.Drawing.Imaging.PixelFormat.Format32bppRgb: format = RGBLuminanceSource.BitmapFormat.RGB32; break; case System.Drawing.Imaging.PixelFormat.Format32bppArgb: format = RGBLuminanceSource.BitmapFormat.ARGB32; break; // 其他格式的處理 default: format = RGBLuminanceSource.BitmapFormat.Unknown; break; } // 獲取寬度(width)和高度(height) int width = image.Width; int height = image.Height; var result = reader.Decode(rawRGB,width,height, format); // do something with the result if (result != null) { Console.WriteLine("內(nèi)容為:"+result.Text); }
調(diào)用示例
到此這篇關(guān)于C#使用ZXing.Net實現(xiàn)識別二維碼和條碼的文章就介紹到這了,更多相關(guān)C#識別二維碼和條碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
asp.net core項目mvc權(quán)限控制:分配權(quán)限
學(xué)習(xí)的最好方法就是動手去做,這里以開發(fā)一個普通的權(quán)限管理系統(tǒng)的方式來從零體驗和學(xué)習(xí)Asp.net Core。項目的整體規(guī)劃大致如下2017-02-02C#?Windows?Forms中實現(xiàn)控件之間的連接線的方法詳解
這篇文章主要為大家詳細介紹了如何在C#?Windows?Forms應(yīng)用程序中實現(xiàn)繪圖工具中多個控件之間的連接線功能,文中的示例代碼講解詳細,需要的可以參考下2024-02-02C#中的應(yīng)用程序接口介紹及實現(xiàn),密封類與密封方法
今天小編就為大家分享一篇關(guān)于C#中的應(yīng)用程序接口介紹及實現(xiàn),密封類與密封方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10