ZXing BarcodeReader Don't Decode Some Barcodes

646 views Asked by At

I am developing a barcode reader with Xamarin.Forms. And I'm trying to scan the image on Android device.

First I select the image from the gallery with Xamarin.Essentials MediaPicker and from the path of this image I get an RGBLuminance with the Dependency class.

Then I am trying to decode this RGBLuminance with the Decode() method of the ZXing BarcodeReaderGeneric class.

The application successfully decodes the barcodes in some images. However, sometimes it returns null when decoding. I might have made a mistake while converting the image to Bitmap or creating the RGBLuminanceSource.

I would like to find out how a class that can decode both color, black and white and grayscale images should be.

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

Command in the ViewModel class:

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

There are 1 answers

1
SubqueryCrunch On

I am using this code in xamarin.android and i never had issues with it:

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

It opens the camera, user takes a pic of barcode and result.Text contains the scanned barcode.