用zxing读取图像中的二维码

 离开一场爱的风雪 发布于 2023-01-30 09:27

我正在使用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;
}

并用于解码:

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

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

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

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

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

任何建议,将不胜感激.

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有