You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET7中使用ZXing.Net读取字节二维码报错:BarcodeReader需泛型参数

解决ZXing.Net中"Using the generic type 'BarcodeReader' requires 1 type arguments"错误

这个错误是因为新版ZXing.Net适配.NET7时,BarcodeReader已改为泛型类,必须指定对应的图像类型参数,不再支持无参构造的非泛型实现。以下是两种可行的修正方案:

方案1:使用System.Drawing.Bitmap(Windows优先)

需要先安装NuGet包 System.Drawing.Common,然后将字节数组转换为Bitmap对象,再传入泛型BarcodeReader<Bitmap>:

using System.Drawing;
using System.IO;
using ZXing;

public static string ReadQRCode(byte[] imageBytes) 
{
    using var memoryStream = new MemoryStream(imageBytes);
    using var bitmap = new Bitmap(memoryStream);

    var barcodeReader = new BarcodeReader<Bitmap>();
    barcodeReader.Options.TryHarder = true; 
    barcodeReader.Options.PossibleFormats = new[] { BarcodeFormat.QR_CODE };

    var result = barcodeReader.Decode(bitmap);
    return result?.Text;
}

方案2:使用ImageSharp(跨平台友好)

如果你的项目需要跨平台运行,推荐使用ImageSharp绑定,先安装NuGet包 ZXing.Net.Bindings.ImageSharp,再用Image<RGB24>作为图像类型:

using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using ZXing;
using ZXing.ImageSharp;

public static string ReadQRCode(byte[] imageBytes) 
{
    using var memoryStream = new MemoryStream(imageBytes);
    using var image = Image.Load<RGB24>(memoryStream);

    var barcodeReader = new BarcodeReader<RGB24>();
    barcodeReader.Options.TryHarder = true; 
    barcodeReader.Options.PossibleFormats = new[] { BarcodeFormat.QR_CODE };

    var result = barcodeReader.Decode(image);
    return result?.Text;
}

注意事项

  • 旧版ZXing.Net的非泛型BarcodeReader已被废弃,升级到适配.NET7的版本后必须改用泛型实现。
  • System.Drawing.Common在.NET7+的Linux/macOS环境中需要额外配置(在项目文件中添加<RuntimeHostConfigurationOption Include="System.Drawing.EnableUnixSupport" Value="true" />),否则会抛出平台不支持异常。

内容的提问来源于stack exchange,提问作者M.Bouabdallah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:20:10