Read QR code from byte using ZXing.Net on .net7

1.5k views Asked by At

This is my code

public static string ReadQRCode(byte[] imageBytes) 
{
    var barcodeReader = new BarcodeReader();
    barcodeReader.Options.TryHarder = true; 
    barcodeReader.Options.PossibleFormats = new[] { BarcodeFormat.QR_CODE };

    var result = barcodeReader.Decode(imageBytes);
    if (result != null) {
        return result.Text;
    }

    return null;
}

But then I got this error message

Using the generic type 'BarcodeReader' requires 1 type arguments

Please guide me to solve the problem

1

There are 1 answers

0
M.Bouabdallah On

This is how I solve it
First you need to install one of the packages from (ZXing.Net.Bindings.*)
First example using

ZXing.Net.Bindings.Windows.Compatibility
Please note this package only works on Windows.

using ZXing;
using ZXing.Common;
using ZXing.QrCode;
using ZXing.Windows.Compatibility;
public static string ReadQRCode(byte[] byteArray)
{
    Bitmap target;
    target = ByteToBitmap(byteArray);
    var source = new BitmapLuminanceSource(target);
    var bitmap = new BinaryBitmap(new HybridBinarizer(source));
    var reader = new QRCodeReader();
    var result = reader.decode(bitmap);
    return result.Text;
}

public static Bitmap ByteToBitmap(byte[] byteArray) 
{
    Bitmap target;
    using (var stream = new MemoryStream(byteArray)) {
         target = new Bitmap(stream);
    }

     return target;
}

Second example using

ZXing.Net.Bindings.ImageSharp.V2

using ZXing;
using ZXing.Common;
using ZXing.ImageSharp;
using ZXing.QrCode;
    public static string ReadQRCode(byte[] byteArray) 
    {
        // Load image from byte array
        Image<Rgba32> image = SixLabors.ImageSharp.Image.Load<Rgba32>(byteArray);
        // Create an instance of ImageSharpLuminanceSource with Rgba32 pixel format
        var luminanceSource = new ImageSharpLuminanceSource<Rgba32>(image);

        var bitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
        var reader = new QRCodeReader();
        var result = reader.decode(bitmap);
        return result. Text;
    }