C#Windows Mobile二维码生成与扫码实现(基于ZXing.NET)

C#写的 Windows Mobile 应用里,二维码功能基本是刚需了,像物流、仓库、门禁系统都靠它传数据。用起来也不麻烦,配上ZXing.NETAForge.NET,一个管生成、一个搞扫码,组合还挺顺手的。

二维码生成那块,用ZXing.BarcodeWriter就行,设定好Format和尺寸,调用Write()方法就能输出一张二维码图。贴个例子:

var writer = new BarcodeWriter {
  Format = BarcodeFormat.QR_CODE,
  Options = new QrCodeEncodingOptions { Width = 256, Height = 256 }
};
var barcodeBitmap = writer.Write("Your Data Here");

再说实时扫码,这部分稍微复杂点,要调用摄像头,捕获帧图像。AForge.Video能帮你搞定设备接入,再把每帧扔给ZXing.MultiFormatReader去解码,识别出来就能直接用:

var videoSource = new VideoCaptureDevice(deviceInfoMoniker);
videoSource.NewFrame += new NewFrameEventHandler(VideoSource_NewFrame);
videoSource.Start();

private void VideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { var frame = eventArgs.Frame; var result = new MultiFormatReader().Decode(ZXing.BitmapSource.Create(frame.Width, frame.Height, frame.Pixels)); if (result != null) { // 解码成功 } }

要注意的点也不少,像性能优化、失败容错这些,在老设备上尤其关键。你可以加个预览窗口,调下图像清晰度,别让用户扫半天扫不出来,那就太伤体验了。

如果你刚好在折腾 C#的移动端开发,想集成个二维码模块,不妨试试这个套路,工具库靠谱,社区资源也多,踩坑少、效率高。

rar 文件大小:242.8KB