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

Win10平板UWP应用实现QR码拍照解码的解决方案求助

解决UWP应用中QR码拍照解码的问题

我之前在Windows 10平板的UWP项目里也碰到过ZXing.Net适配的坑,折腾了一阵终于找到可行的方案,分享给你:

第一步:安装正确的NuGet包

别纠结ZXing.Net.Mobile了,直接安装ZXing.Net的稳定版(最新版即可),这个包对UWP的兼容性更靠谱。可以通过NuGet包管理器搜索安装,或者用Package Manager Console执行命令:

Install-Package ZXing.Net

第二步:修改拍照后的解码逻辑

你现有的拍照代码没问题,只需要在获取到StorageFile后,把图片转换成ZXing能识别的格式再解码。这里关键是要把图片转成灰度图,并且用UWP专属的BitmapLuminanceSource:

var bounds = ApplicationView.GetForCurrentView().VisibleBounds;
var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel;
var size = new Size(bounds.Width * scaleFactor, bounds.Height * scaleFactor);

CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.CroppedSizeInPixels = new Size(size.Width, size.Height);

StorageFile file = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (file != null)
{
    try
    {
        // 读取照片文件并转换为SoftwareBitmap
        using (var stream = await file.OpenAsync(FileAccessMode.Read))
        {
            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
            SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
            
            // 转换为ZXing需要的灰度格式(Gray8)
            SoftwareBitmap grayBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Gray8);
            
            // 创建UWP兼容的LuminanceSource
            var luminanceSource = new ZXing.Windows.Compatibility.BitmapLuminanceSource(grayBitmap);
            var binaryBitmap = new ZXing.BinaryBitmap(new ZXing.HybridBinarizer(luminanceSource));
            
            // 初始化QR码阅读器并解码
            var qrReader = new ZXing.QrCode.QRCodeReader();
            var result = qrReader.Decode(binaryBitmap);
            
            if (result != null)
            {
                string decodedContent = result.Text;
                // 这里处理解码后的内容,比如显示到界面或者业务逻辑处理
                // 例如:await new MessageDialog($"解码结果:{decodedContent}").ShowAsync();
            }
            else
            {
                // 提示用户未识别到QR码
            }
        }
    }
    catch (Exception ex)
    {
        // 处理异常,比如拍照失败、解码出错等
    }
}

第三步:确保权限配置正确

在Package.appxmanifest里必须添加摄像头权限,否则无法调用相机:

<Capabilities>
    <DeviceCapability Name="webcam" />
    <!-- 如果需要保存照片到本地,还可以添加图片库权限 -->
    <Capability Name="picturesLibrary" />
</Capabilities>

常见问题排查

  • 如果解码失败,先检查是否转换成了Gray8格式的位图,ZXing对灰度图的识别率最高;
  • 确保使用的是ZXing.Windows.Compatibility命名空间下的BitmapLuminanceSource,而不是桌面版的实现;
  • 拍照时尽量让QR码占据画面中心,避免模糊或者倾斜太严重,提升识别成功率。

内容的提问来源于stack exchange,提问作者Mr. Developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:33:49