C# with ZXing.Net: Decoding the QR code

19,533

Just call function. Also, replace ... with your handling

public Result decode(Uri uri)
{
         Bitmap image;
         try
         {
            image = (Bitmap) Bitmap.FromFile(uri.LocalPath);
         }
         catch (Exception)
         {
            throw new FileNotFoundException("Resource not found: " + uri);
         }

         using (image)
         {
            LuminanceSource source;
            source = new BitmapLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap);
            if (result != null)
            {
                ... code found
            }
            else
            {
                ... no code found
            }
            return result;
         }
}
Share:
19,533
Antares
Author by

Antares

Updated on June 04, 2022

Comments

  • Antares
    Antares almost 2 years

    I'm new to C# and got problem with QR code decoding using ZXing.Net. The application launches with no errors, but I get nothing in the result string. I think the problem could be in RGBLuminanceSource().

    private static byte[] ToByteArray(Image img)
    {
        byte[] byteArray = new byte[0];
        using (MemoryStream stream = new MemoryStream())
        {
            img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
            stream.Close();
    
            byteArray = stream.ToArray();
        }
        return byteArray;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        *** SOME OTHER CODE HERE ***
    
        Bitmap BitmapImage = new Bitmap(@"D:\1.png"); 
    
        QRCodeReader reader = new QRCodeReader();
        LuminanceSource source = new RGBLuminanceSource(ToByteArray(BitmapImage), BitmapImage.Width, BitmapImage.Height);
    
        var binarizer = new HybridBinarizer(source);
        var binBitmap = new BinaryBitmap(binarizer);
        string result = reader.decode(binBitmap).Text;
    
        *** SOME OTHER CODE HERE ***
    }
    
  • Antares
    Antares about 9 years
    Thank you! BitmapLuminanceSource helped me!
  • Badhon Ashfaq
    Badhon Ashfaq over 8 years
    This Helped me.Thanks a lot :)