使用zxing.net组件,读取BitmapSource中的二维码。简单使用方法如下:
private void DecodeQrCode() { if (QrCodeSource.CanFreeze) { QrCodeSource.Freeze(); } using (var bitmap = BitmapSourceToBitmap(QrCodeSource)) { var source = new BitmapLuminanceSource(bitmap); var bBitmap = new BinaryBitmap(new HybridBinarizer(source)); var result = new MultiFormatReader().decode(bBitmap); ResultValue = result?.Text; } }
解析要简单很多:
private void EncodeToQrCode() { var qrCodeWriter = new QRCodeWriter(); var result = qrCodeWriter.encode(Value, BarcodeFormat.QR_CODE, 200, 200); var barcodeWriter = new BarcodeWriter(); using (var bitmap = barcodeWriter.Write(result)) { QrCodeSource = null; QrCodeSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } }
ImageSource到Bitmap的转换:
public static Bitmap BitmapSourceToBitmap(BitmapSource bitmapImage) { using (var outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage)); enc.Save(outStream); return new Bitmap(outStream); } }
存在内存泄漏问题。