Xamarin.Forms ZXing BarcodeReaderGeneric 在扫描图库中的图像时返回 null

问题描述

我正在使用 Xamarin.Forms 开发条形码阅读器。我正在尝试在 Android 设备上扫描图像。

首先,我使用 Xamarin.Essentials MediaPicker 从图库中选择图像,然后从该图像的路径中获得具有 Dependency 类的 RGBluminance

然后我尝试使用 ZXing BarcodeReaderGeneric 类的 Decode() 方法解码这个 RGBluminance。但是,结果总是返回 null。

这是我的演示项目:https://onedrive.live.com/?authkey=%21AFLjjM91wgZkBGU&cid=58BE2C2C3447FFA2&id=58BE2C2C3447FFA2%219829&parId=root&action=locate

viewmodel 类中的命令:

        public ICommand PickCommand => new Command(PickImage);
        private async void PickImage()
        {
            var pickResult = await MediaPicker.PickPhotoAsync(new MediaPickerOptions
            {
                Title = "Select a barcode."
            });
            var path = pickResult.FullPath;

            var RGBluminance = DependencyService.Get<Iluminance>().GetRGBluminanceSource(path);
            var reader = new BarcodeReaderGeneric();
            var result = reader.Decode(RGBluminance); // result always null.
        }

Android 中依赖类的方法

        public RGBluminanceSource GetRGBluminanceSource(string imagePath)
        {
            
            if (File.Exists(imagePath))
            {
                Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeFile(imagePath);
                List<byte> rgbBytesList = new List<byte>();
                for (int y = 0; y < bitmap.Height; y++)
                {
                    for (int x = 0; x < bitmap.Width; x++)
                    {
                        var c = new Android.Graphics.Color(bitmap.GetPixel(x,y));
                        rgbBytesList.AddRange(new[] { c.A,c.R,c.G,c.B });
                    }
                }
                byte[] rgbBytes = rgbBytesList.ToArray();
                return new RGBluminanceSource(rgbBytes,bitmap.Height,bitmap.Width,RGBluminanceSource.Bitmapformat.RGB32);
            }
            return null;
        }

解决方法

你应该换行

return new RGBLuminanceSource(rgbBytes,bitmap.Height,bitmap.Width,RGBLuminanceSource.BitmapFormat.RGB32);

return new RGBLuminanceSource(rgbBytes,RGBLuminanceSource.BitmapFormat.RGB32);

为了更准确地使用 RGB 格式,您应该

  • 将 RGBLuminanceSource.BitmapFormat.RGB32 更改为 RGBLuminanceSource.BitmapFormat.ARGB32
  • 或更改 rgbBytesList.AddRange(new[] { c.A,c.R,c.G,c.B });到 rgbBytesList.AddRange(new[] { c.R,c.B,c.A });
,

你可以试试这张照片吗?

Picture One Picture Two