问题描述
我正在使用 Xamarin.Forms 开发条形码阅读器。我正在尝试在 Android 设备上扫描图像。
首先,我使用 Xamarin.Essentials MediaPicker 从图库中选择图像,然后从该图像的路径中获得具有 Dependency 类的 RGBluminance。
然后我尝试使用 ZXing BarcodeReaderGeneric 类的 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
包含扫描的条码。