.NET 8中读取PDF内条形码下方数字的技术求助
.NET 8下读取PDF中Code128C条形码下方数字的解决方案
问题分析
之前的代码未明确指定条码格式,且未对图片做针对性预处理,同时未限制识别区域,导致ZXing无法精准定位并识别Code128C条码。以下是优化后的解决方案:
优化步骤及代码实现
- 指定条码格式:明确设置识别Code128格式,减少无效扫描尝试
- 裁剪识别区域:聚焦PDF右上角的条码区域,排除无关内容干扰
- 图片预处理:转灰度+增强对比度,提升条码清晰度
- 依赖包准备:安装
ZXing.Net、PdfiumViewer、System.Drawing.Common(.NET 8需手动引入)
using System.Drawing; using System.Drawing.Imaging; using PdfiumViewer; using ZXing; using ZXing.Common; using System.Collections.Generic; public string ReadBarcodeFromPdf(string pdfPath) { using (var document = PdfDocument.Load(pdfPath)) { // 300DPI渲染PDF第一页,保证条码清晰度 using (var fullPageImage = document.Render(0, 300, 300, true)) { // 裁剪右上角条码区域(需根据实际PDF调整坐标参数) var barcodeRegion = new Rectangle( fullPageImage.Width - fullPageImage.Width / 4, // 起始X:右侧1/4处 0, // 起始Y:顶部 fullPageImage.Width / 4, // 区域宽度 fullPageImage.Height / 5 // 区域高度 ); using (var targetImage = fullPageImage.Clone(barcodeRegion, fullPageImage.PixelFormat)) { // 预处理图片:转灰度+增强对比度 using (var processedImage = ConvertToEnhancedGrayscale(targetImage)) { var reader = new BarcodeReader() { AutoRotate = true, Options = new DecodingOptions { TryHarder = true, TryInverted = true, // 明确指定仅识别Code128条码 PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.CODE_128 } } }; var result = reader.Decode((Bitmap)processedImage); return result?.Text; } } } } } // 图片预处理辅助方法:转灰度并增强对比度 private Bitmap ConvertToEnhancedGrayscale(Bitmap originalImage) { var grayscaleBitmap = new Bitmap(originalImage.Width, originalImage.Height); using (var graphics = Graphics.FromImage(grayscaleBitmap)) { // 灰度转换矩阵 var colorMatrix = new ColorMatrix(new float[][] { new float[] {0.299f, 0.299f, 0.299f, 0, 0}, new float[] {0.587f, 0.587f, 0.587f, 0, 0}, new float[] {0.114f, 0.114f, 0.114f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); var imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix(colorMatrix); imageAttributes.SetThreshold(0.5f); // 调整阈值增强黑白对比度 graphics.DrawImage(originalImage, new Rectangle(0, 0, originalImage.Width, originalImage.Height), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, imageAttributes); } return grayscaleBitmap; }
额外注意事项
- 调整裁剪区域:若识别失败,可先将
fullPageImage保存为本地图片,查看条码实际位置后修改barcodeRegion的坐标参数 - 阈值调整:根据图片清晰度,修改
SetThreshold的参数(0~1之间),优化对比度 - 依赖版本:确保使用最新稳定版NuGet包,避免兼容性问题
内容的提问来源于stack exchange,提问作者Pelle Woah
相关产品推荐
相关产品推荐

