需求:圖像識別出一張圖片中的二維碼或者條形碼,并讀取其中內容。
一、安裝庫(特別注意,網上很多都沒說清楚)
如果是基于.net framework,則安裝ZXing.Net(建議0.14.0版本左右,具體看實際,版本太高,部分接口發生變化)
如果是基于.Net Standard 2.0 or .NET CORE 3.0/3.1 or .NET 5.0 or higher,則安裝ZXing.Net.Bindings.Windows.Compatibility
二、WinForm示例代碼(含關鍵優化)
using ZXing.Common;
using ZXing;
using ZXing.Windows.Compatibilitypublic partial class MainForm : Form
{public MainForm(){InitializeComponent();}// 選擇圖片按鈕點擊事件private void btnSelectImage_Click(object sender, EventArgs e){OpenFileDialog dialog = new OpenFileDialog();dialog.Filter = "圖片文件|*.jpg;*.png;*.bmp";if (dialog.ShowDialog() == DialogResult.OK){pictureBox1.Image = Image.FromFile(dialog.FileName);}}// 識別條碼按鈕點擊事件private void btnDecode_Click(object sender, EventArgs e){if (pictureBox1.Image == null){MessageBox.Show("請先選擇圖片");return;}var bitmap = new Bitmap(pictureBox1.Image);// 創建解碼器(關鍵配置)var reader = new BarcodeReader{Options = new DecodingOptions{PossibleFormats = new[] { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, // 條形碼BarcodeFormat.EAN_13 },TryHarder = true, // 提高復雜圖像識別率CharacterSet = "UTF-8" // 支持中文}};// 識別條碼(支持多碼)Result[] results = reader.DecodeMultiple(bitmap);if (results != null){foreach (Result result in results){txtResult.AppendText($"? 識別成功!類型:{result.BarcodeFormat},內容:{result.Text}\r\n");}}else{txtResult.Text = "? 識別失敗:未檢測到有效條碼";}}
}
三、識別率優化技巧
//1. 圖像預處理(解決模糊/低對比度問題)
csharp
// 轉換為灰度圖+二值化
var luminanceSource = new BitmapLuminanceSource(bitmap);
var binarizer = new HybridBinarizer(luminanceSource);
var binBitmap = new BinaryBitmap(binarizer);Result result = reader.Decode(binBitmap); // 使用處理后的圖像
//2. 多尺度識別(針對小尺寸條碼)
csharp
for (double scale = 1.0; scale <= 2.0; scale += 0.2)
{var scaledBitmap = new Bitmap(bitmap, new Size((int)(bitmap.Width * scale), (int)(bitmap.Height * scale)));Result result = reader.Decode(scaledBitmap);if (result != null) break;
}
//3. 區域裁剪(復雜背景中定位條碼)
csharp
// 假設已知條碼在圖像右下角1/4區域
Rectangle cropArea = new Rectangle(bitmap.Width / 2, bitmap.Height / 2, bitmap.Width / 2, bitmap.Height / 2
);using (Bitmap cropped = bitmap.Clone(cropArea, bitmap.PixelFormat))
{Result result = reader.Decode(cropped);
}