用zxing读取图像中的二维码

Dan*_*Dan 7 c# qr-code zxing

我正在使用C#库来读取QRCodes.我发现的很多样本都基于zxing的旧版本,其中RGBLuminanceSource构造函数仍然采用位图.在最新版本中,RGBLuminanceSource只接受byte [].我试图将位图转换为byte [],但解码结果始终为null.

这是我用于转换的代码:

private byte[] GetRGBValues(Bitmap bmp)
{
  // Lock the bitmap's bits. 
  System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height);
  System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

  // Get the address of the first line.
  IntPtr ptr = bmpData.Scan0;

  // Declare an array to hold the bytes of the bitmap.
  int bytes = bmpData.Stride * bmp.Height;
  byte[] rgbValues = new byte[bytes];
  // Copy the RGB values into the array.
  System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
  bmp.UnlockBits(bmpData);

  return rgbValues;
}
Run Code Online (Sandbox Code Playgroud)

并用于解码:

Bitmap bitmap = Bitmap.FromFile(@"C:\QRimages.jpg") as Bitmap;
LuminanceSource source = new RGBLuminanceSource(GetRGBValues(bitmap), bitmap.Width, bitmap.Height);

var binarizer = new HybridBinarizer(source);
var binBitmap = new BinaryBitmap(binarizer);
QRCodeReader reader = new QRCodeReader();
var result = reader.decode(binBitmap);
Run Code Online (Sandbox Code Playgroud)

不知何故,结果始终为null.

另外,我们的要求是我们必须使用相机拍摄的图像.我试过这个:

Bitmap bitmap = Bitmap.FromFile(@"C:\QRimages.jpg") as Bitmap;
BarcodeReader reader = new BarcodeReader { AutoRotate = true, TryHarder = true };
Result result = reader.Decode(bitmap);
Run Code Online (Sandbox Code Playgroud)

它仅适用于我在线下载的QR图像,但是如果我打印出该图像并用手机拍照,那么尝试处理该图像,结果返回null.

任何建议,将不胜感激.

这是我正在使用的图像: QR码图片