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

WPF中ZXing摄像头扫码失败求助:仅支持Bitmap解码

我来帮你搞定这个WPF+ZXing扫码的问题,你遇到的核心问题主要有两个:一是WPF摄像头捕获的图像格式和ZXing需要的System.Drawing.Bitmap不兼容,二是你的定时器间隔设置得太夸张了(5分钟扫一次肯定没法实时用啊😅)。下面给你一步步解决:

问题拆解

你当前代码的两个关键问题:

  • 定时器间隔设为5分钟(new TimeSpan(0,5,0)),完全没法实现实时扫描,必须改成毫秒级间隔
  • WPF中摄像头输出的是BitmapSource/WriteableBitmap,直接转ZXing需要的Bitmap容易出现格式错误或空引用
解决方案

1. 先把定时器改回合理间隔

把扫描频率调整到50毫秒左右,这样才能实时捕获画面:

dispatcherTimer.Interval = TimeSpan.FromMilliseconds(50);

2. 写个靠谱的图像转换方法

专门处理WPF图像到System.Drawing.Bitmap的转换,避免格式兼容问题:

private System.Drawing.Bitmap ConvertWpfBitmapToDrawingBitmap(BitmapSource bitmapSource)
{
    using (MemoryStream stream = new MemoryStream())
    {
        BitmapEncoder encoder = new BmpBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
        encoder.Save(stream);
        return new System.Drawing.Bitmap(stream);
    }
}

3. 完整的扫码逻辑示例

假设你已经把摄像头画面绑定到了名为imgCamera的WPF Image控件,完整的Tick事件处理代码如下:

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    // 先确保摄像头画面已加载
    if (imgCamera.Source == null) return;

    try
    {
        // 转换图像格式
        using (var drawingBitmap = ConvertWpfBitmapToDrawingBitmap((BitmapSource)imgCamera.Source))
        {
            // 初始化ZXing二维码解码器
            var barcodeReader = new BarcodeReader
            {
                Options = new ZXing.Common.DecodingOptions
                {
                    PossibleFormats = new List<ZXing.BarcodeFormat> { ZXing.BarcodeFormat.QR_CODE },
                    TryHarder = true // 提升模糊、倾斜二维码的识别成功率
                }
            };

            // 执行解码
            var scanResult = barcodeReader.Decode(drawingBitmap);
            if (scanResult != null)
            {
                // 扫码成功,处理结果
                MessageBox.Show($"扫码成功:{scanResult.Text}");
                dispatcherTimer.Stop(); // 可选:扫到后暂停定时器
            }
        }
    }
    catch (Exception ex)
    {
        // 捕获异常避免程序崩溃,同时输出错误信息便于调试
        System.Diagnostics.Debug.WriteLine($"扫码出错:{ex.Message}");
    }
}

4. 额外注意事项

  • 窗口关闭时记得释放摄像头资源:比如你的摄像头实例是LocalWebCam,就加一句LocalWebCam.Stop();
  • 如果摄像头输出的是WriteableBitmap,上面的转换方法同样适用
  • 可以根据需求调整TryHarder参数和PossibleFormats,平衡识别效率和范围

内容的提问来源于stack exchange,提问作者Adri1511

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:12:30