使用ZXing.NET 0.16.0扫码时遇HResult=0x80070057错误求助
ZXing条码解码报错:Source must be non-null 排查与解决
错误信息
System.ArgumentException HResult=0x80070057 Message=Source must be non-null. Source=zxing StackTrace: at ZXing.Binarizer..ctor(LuminanceSource source) at ZXing.Common.GlobalHistogramBinarizer..ctor(LuminanceSource source) at ZXing.Common.HybridBinarizer..ctor(LuminanceSource source) at ZXing.BarcodeReaderGeneric.<>c.<.cctor>b__40_0(LuminanceSource luminanceSource) at ZXing.BarcodeReaderGeneric.Decode(LuminanceSource luminanceSource) at ZXing.BarcodeReader.Decode(Byte[] barcodeBitmap) at FileApi.Controllers.ToolController.BarcodeZXingReader(QrCodeParam inputParam) in C:\Data\GitRepo\FileApi\FileApi\Controllers\ToolController.cs:line 225 at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()
问题代码
Byte[] byteArray = Convert.FromBase64String(inputParam.Input); // Create an instance of BarcodeReader class var barcodeReader = new BarcodeReader(); // Set the barcode format you want to read barcodeReader.Options.PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.QR_CODE, BarcodeFormat.CODE_128, BarcodeFormat.EAN_13 }; var barcodeResult = barcodeReader.Decode(byteArray); if (barcodeResult != null) return barcodeResult; else return "failed read it";
原因分析
- 传入的Base64字符串转换后的byte数组无法被ZXing解析为有效图像,导致内部创建
LuminanceSource实例时返回null,触发"Source must be non-null"异常。 - 具体诱因包括:
inputParam.Input为空字符串或无效的Base64格式- Base64对应的是损坏的图像、非图像格式的数据
- ZXing旧版本对直接传入byte数组的图像格式支持有限(比如仅支持BMP,而传入的是JPG/PNG)
解决方案
1. 校验Base64输入有效性
在转换前检查输入是否为空,并捕获格式异常,避免无效数据进入解码流程:
if (string.IsNullOrWhiteSpace(inputParam.Input)) { return "输入的Base64字符串为空"; } byte[] byteArray; try { byteArray = Convert.FromBase64String(inputParam.Input); } catch (FormatException ex) { return $"无效的Base64格式:{ex.Message}"; }
2. 改用Bitmap/Image方式解码
避免直接传入byte数组的兼容性问题,先将byte数组转为Bitmap再解码:
using (var ms = new MemoryStream(byteArray)) using (var bitmap = new Bitmap(ms)) { var barcodeResult = barcodeReader.Decode(bitmap); return barcodeResult != null ? barcodeResult : "解码失败"; }
注意:.NET Core/.NET 5+环境需要单独安装
System.Drawing.CommonNuGet包。
3. 升级ZXing版本或适配对应绑定包
旧版本ZXing对部分图像格式支持不佳,升级到最新稳定版的ZXing.Net,或根据运行环境选择对应的绑定包(比如ZXing.Net.Bindings.WindowsMediaFoundation),提升图像解析兼容性。
4. 添加异常捕获增强错误处理
在解码环节捕获异常,返回更明确的错误信息:
try { var barcodeResult = barcodeReader.Decode(byteArray); return barcodeResult != null ? barcodeResult : "解码失败"; } catch (ArgumentException ex) { return $"解码异常:{ex.Message}"; } catch (Exception ex) { return $"未知错误:{ex.Message}"; }
内容的提问来源于stack exchange,提问作者toha
相关产品推荐
相关产品推荐

