C#with ZXing.Net:解码QR码

时间:2015-02-17 12:42:05

标签: c# decode qr-code zxing

我是 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 个答案:

答案 0 :(得分:4)

只需调用函数。另外,用你的处理替换......

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