ZXing条形码阅读器不解码某些条形码



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

首先,我用Xamarin.Essentials MediaPicker从图库中选择图像,并从该图像的路径中获得一个带有Dependency类的RGBLuminance。

然后我尝试使用ZXingBarcodeReaderGeneric类的decode((方法来解码这个RGBLuminance。

该应用程序成功解码了某些图像中的条形码。但是,有时在解码时会返回null。我可能在将图像转换为位图或创建RGBLuminanceSource时犯了一个错误。

我想了解一个可以解码彩色、黑白和灰度图像的类应该如何。

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.Width, bitmap.Height, RGBLuminanceSource.BitmapFormat.RGB32);
}
return null;
}

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); 
}

我在xamarin.android中使用这段代码,我从未遇到过问题:

var scanner = new MobileBarcodeScanner();
var result = await scanner.Scan(_context, MobileBarcodeScanningOptions.Default);

它打开相机,用户拍摄条形码的照片,result.Text包含扫描的条形码。

最新更新