Search code examples
c#asp.net-coreqr-codebarcodezxing

ZXing.Net decode barcode giving Error - Cannot convert from 'System.Drawing.Bitmap' to 'ZXing.LuminanceSource'


I am using ZXing.Net 0.16.4.0 to decode qr code files which are kept inside the 'wwwroot/qrr' folder, but i am getting compile time error:

Cannot convert from 'System.Drawing.Bitmap' to 'ZXing.LuminanceSource'

My Code:

string[] files = Directory.GetFiles("wwwroot/qrr");
foreach (string file in files)
{
    // create a barcode reader instance
    IBarcodeReader reader = new BarcodeReader();
    // load a bitmap
    var barcodeBitmap = (Bitmap)Image.FromFile("wwwroot/qrr/" + Path.GetFileName(file));

    // detect and decode the barcode inside the bitmap
    var result = reader.Decode(barcodeBitmap);
}

The error is in the last line of code:

 var result = reader.Decode(barcodeBitmap);

My application is in ASP.NET Core and I am using the official docs code but they are not working. Please help?

Update

I noticed that the ZXing pacakage when added to ASP.NET Core application, then it's ZXing.IBarcodeReader has a missing Decode overloaded method:

IBarcodeReader has only 2 overloades of decode method:

Result Decode(byte[] rawRGB, int width, int height, RGBLuminanceSource.BitmapFormat format);
Result Decode(LuminanceSource luminanceSource);

But when you install this package in .Net 4.6.1 framework then there is one more overload method:

Result Decode(Bitmap barcodeBitmap);

How can an package gives different codes in different frameworks?


Solution

  • Since you're using ASP.NET Core, I'm supposing you've added an reference to the package of ZXing.Net.Bindings.CoreCompat.System.Drawing . You need change your code as below :

    string[] files = Directory.GetFiles("wwwroot/qrr");
    foreach (string file in files)
    {
        // create a barcode reader instance
        IBarcodeReader reader = new BarcodeReader();
        BarcodeReader reader = new BarcodeReader();
        // load a bitmap
        var barcodeBitmap = (Bitmap)Image.FromFile("wwwroot/qrr/" + Path.GetFileName(file));
    
        // detect and decode the barcode inside the bitmap
        var result = reader.Decode(barcodeBitmap);
    }
    

    Note this .Decode() is an extension method of IBarcodeReaderGeneric instead of the IBarcodeReader