C# 实战:利用ZXing.Net实现一维码/二维码的生成、定制化与解析

张开发
2026/4/13 13:01:37 15 分钟阅读

分享文章

C# 实战:利用ZXing.Net实现一维码/二维码的生成、定制化与解析
1. 为什么选择ZXing.Net处理条码在C#项目中集成条码功能时开发者常面临第三方库的选择难题。ZXing.Net作为ZXingZebra Crossing的.NET移植版本已经成为处理一维码/二维码的事实标准。我曾在多个商业项目中采用这个库最直观的感受是它的轻量级设计和工业级稳定性——某次需要同时处理2000个物流条码时连续运行8小时未出现内存泄漏。与其他库相比ZXing.Net有三个突出优势格式支持全面支持包括CODE_128、QR_CODE、EAN-13等20种编码格式解析能力强即使图片存在轻微变形或污损仍可识别零依赖单个DLL文件即可实现生成与解析功能提示商业项目建议使用NuGet稳定版个人项目可尝试GitHub最新代码获取实验性功能2. 环境配置与基础准备2.1 安装与引用通过NuGet安装是最推荐的方式我在Visual Studio 2022中的实际操作步骤右键项目选择管理NuGet程序包搜索框中输入ZXing.Net选择官方发布的稳定版本当前最新为0.16.8点击安装后自动添加所需引用核心命名空间引用示例using ZXing; using ZXing.Common; using ZXing.QrCode;2.2 基础参数理解生成条码前需要了解的三个核心参数Margin边距控制条码四周空白区域建议值2-5像素PureBarcode是否隐藏下方文本涉及UI展示时需特别注意ErrorCorrectionLevel二维码容错级别L7%, M15%, Q25%, H30%3. 一维码生成实战3.1 基础生成方案以物流行业常用的CODE_128格式为例这是我在电商系统中使用的优化版本public Bitmap GenerateBarcode(string content, int width 300, int height 100) { var writer new BarcodeWriter { Format BarcodeFormat.CODE_128, Options new EncodingOptions { Width width, Height height, Margin 3, PureBarcode false //显示下方文本 } }; return writer.Write(content); }3.2 常见问题排查在实际项目中遇到过几个典型问题扫描器无法识别检查是否误用ITF格式支付宝/微信不支持文本显示不全调整Height参数或使用特定字体生成速度慢复用BarcodeWriter实例而非每次创建新实例4. 二维码高级应用4.1 带Logo的二维码优化方案这是经过多次迭代的稳定版本重点解决了Logo边缘白边问题public Bitmap GenerateQRCodeWithLogo(string text, Image logo, int size 500, int logoSizePercent 20) { var options new QrCodeEncodingOptions { DisableECI true, CharacterSet UTF-8, Width size, Height size, ErrorCorrection ErrorCorrectionLevel.H }; var writer new BarcodeWriter { Format BarcodeFormat.QR_CODE, Options options }; var matrix writer.Encode(text); var qrBitmap writer.Write(matrix); // 计算Logo尺寸 int logoWidth (int)(size * logoSizePercent / 100f); int logoHeight logoWidth * logo.Height / logo.Width; // 高质量绘制 using (var graphics Graphics.FromImage(qrBitmap)) { graphics.CompositingQuality CompositingQuality.HighQuality; graphics.InterpolationMode InterpolationMode.HighQualityBicubic; // 居中定位 int x (size - logoWidth) / 2; int y (size - logoHeight) / 2; // 添加白色背景可选 graphics.FillRectangle(Brushes.White, x, y, logoWidth, logoHeight); graphics.DrawImage(logo, x, y, logoWidth, logoHeight); } return qrBitmap; }4.2 动态二维码实践结合WPF实现实时更新的电子票务二维码// 在ViewModel中 private string _dynamicContent; public string DynamicContent { get _dynamicContent; set { _dynamicContent value; OnPropertyChanged(); UpdateQrCode(); } } private void UpdateQrCode() { var writer new BarcodeWriter { Format BarcodeFormat.QR_CODE, Options new QrCodeEncodingOptions { Width 400, Height 400, Margin 1 } }; QrCodeImage writer.Write(DynamicContent); }5. 条码解析技术5.1 基础解析方法支持多种图片输入方式的通用解析方案public string DecodeBarcode(object input) { var reader new BarcodeReader { Options new DecodingOptions { PossibleFormats new ListBarcodeFormat { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128 }, TryHarder true } }; Bitmap bitmap input switch { string path new Bitmap(path), byte[] bytes (Bitmap)Image.FromStream(new MemoryStream(bytes)), Bitmap bmp bmp, _ throw new ArgumentException(Unsupported input type) }; var result reader.Decode(bitmap); return result?.Text ?? Decode failed; }5.2 性能优化技巧处理大批量扫描时采用的优化策略实例复用创建全局静态BarcodeReader实例预处理图像先转换为灰度图再解析多线程处理使用Parallel.For处理图片集合6. 实用扩展功能6.1 图片保存与加载增强版文件对话框集成方案public static class ImageDialogHelper { public static Bitmap OpenImage() { using var dialog new OpenFileDialog { Title 选择条码图片, Filter 图像文件|*.jpg;*.png;*.bmp|所有文件|*.*, CheckFileExists true }; return dialog.ShowDialog() DialogResult.OK ? new Bitmap(dialog.FileName) : null; } public static void SaveImage(Image image) { using var dialog new SaveFileDialog { Title 保存条码图片, Filter PNG图像|*.png|JPEG图像|*.jpg|位图|*.bmp, DefaultExt .png }; if (dialog.ShowDialog() DialogResult.OK) { var format Path.GetExtension(dialog.FileName).ToLower() switch { .jpg ImageFormat.Jpeg, .bmp ImageFormat.Bmp, _ ImageFormat.Png }; image.Save(dialog.FileName, format); } } }6.2 Base64转换增强版支持自动检测图像格式的转换工具public static class Base64Converter { public static string ImageToBase64(Image image, ImageFormat format null) { format ?? ImageFormat.Png; // 默认PNG格式 using var ms new MemoryStream(); image.Save(ms, format); return Convert.ToBase64String(ms.ToArray()); } public static Image Base64ToImage(string base64String) { try { byte[] bytes Convert.FromBase64String(base64String); using var ms new MemoryStream(bytes); return Image.FromStream(ms); } catch { return null; } } }7. 企业级应用建议在金融级应用中我们还需要考虑安全防护对生成的二维码进行数字签名版本控制保持ZXing.Net版本统一日志记录记录条码生成/解析的关键操作一个经过验证的生产环境配置示例services.AddSingletonIBarcodeProcessor(provider new BarcodeProcessor { DefaultQrOptions new QrCodeEncodingOptions { Width 600, Height 600, ErrorCorrection ErrorCorrectionLevel.H, CharacterSet UTF-8 }, Logger provider.GetRequiredServiceILoggerBarcodeProcessor() });

更多文章