目录

写在前面

代码实现

调用示例

写在前面

上一篇写了 C# 使用ZXing.Net生成二维码和条码-CSDN博客 

使用ZXing.Net解码非常简单,事实上就只用一行代码就好了,这么简单那为什么还要贴在这里呢,原因是开始时,在网上看资料看到一篇文章,稀里哗啦写了一堆代码,然后拿来运行一下,竟然还得不到预期的结果;看了下用了最复杂的方式,调用了参数最多的重载函数,问题却没有解决,所以在网上查找资料,鉴别成本有时候是很高的;大部分的代码拷来拷去,完全不做验证,实在是浪费时间;最简单有效的办法还是尽量往信息的源头去追溯,比如官网文档、GitHub上的源码介绍、业内大牛的文章等。最好还是自己把代码跑一遍,不仅可以确认也能加深印象,下次碰到同类问题或许拿来就用了,效率就是这么提升的。

官网: GitHub - micjahn/ZXing.Net: .Net port of the original java-based barcode reader and generator library zxing 

代码实现

var reader = new BarcodeReader();

var result = reader.Decode((Bitmap)pictureBox1.Image);

if (result != null)

{

lblMessage.Text = result.Text;

}

else

{

lblMessage.Text = "None";

}

反面教材原代码如下:

// create a barcode reader instance

IBarcodeReader reader = new BarcodeReader();

// 加载图片文件

Bitmap image = new Bitmap("D:\\PrideJoy\\Zxing.Demo\\Zxing.demo\\bin\\Debug\\net7.0\\qr-image.jpg");

// 获取rawRGB数据

Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);

System.Drawing.Imaging.BitmapData bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, image.PixelFormat);

IntPtr ptr = bmpData.Scan0;

int bytes = Math.Abs(bmpData.Stride) * image.Height;

byte[] rawRGB = new byte[bytes];

System.Runtime.InteropServices.Marshal.Copy(ptr, rawRGB, 0, bytes);

image.UnlockBits(bmpData);

// 获取格式(format)

RGBLuminanceSource.BitmapFormat format;

switch (image.PixelFormat)

{

case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:

format = RGBLuminanceSource.BitmapFormat.Gray8;

break;

case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:

format = RGBLuminanceSource.BitmapFormat.Gray16;

break;

case System.Drawing.Imaging.PixelFormat.Format24bppRgb:

format = RGBLuminanceSource.BitmapFormat.RGB24;

break;

case System.Drawing.Imaging.PixelFormat.Format32bppRgb:

format = RGBLuminanceSource.BitmapFormat.RGB32;

break;

case System.Drawing.Imaging.PixelFormat.Format32bppArgb:

format = RGBLuminanceSource.BitmapFormat.ARGB32;

break;

// 其他格式的处理

default:

format = RGBLuminanceSource.BitmapFormat.Unknown;

break;

}

// 获取宽度(width)和高度(height)

int width = image.Width;

int height = image.Height;

var result = reader.Decode(rawRGB,width,height, format);

// do something with the result

if (result != null)

{

Console.WriteLine("内容为:"+result.Text);

}

调用示例

精彩链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。