使用ZXing.Net的C#:解码QR码

4

我刚接触C#,在使用ZXing.Net解码QR码时遇到了问题。应用程序启动没有出现任何错误,但是结果字符串里却为空。我认为问题可能出在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 ***
}
1个回答

12

只需调用函数。同时,将...替换为您的处理

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

1
谢谢!BitmapLuminanceSource帮了我一个大忙! - Antares
1
这帮了我很大的忙。非常感谢 :) - Badhon Ashfaq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接