Introduction: If you need to use the following QR code image generation function in the WPF form program, you can implement it through the method in this article.
Steps: 1. Download ZXing on the http://zxingnet.codeplex.com/ site. .Net 2. After downloading, you can see that there are different targets. .NET version of the dll file that references the correct dll in your project 3. Then refer to the System.Drawing assembly in your project 4. In the window where you need to generate a QR code, add the following code:
- // 注销对象方法API
- [DllImport("gdi32")]
- static extern int DeleteObject(IntPtr o);
- /**
- * 创建二维码图片
- */
- private ImageSource createQRCode(String content, int width, int height)
- {
- EncodingOptions options;//包含一些编码、大小等的设置
- BarcodeWriter write = null;//用来生成二维码,对应的BarcodeReader用来解码
- options = new QrCodeEncodingOptions
- {
- DisableECI = true,
- CharacterSet = "UTF-8",
- Width = width,
- Height = height,
- Margin = 0
- };
- write = new BarcodeWriter();
- write.Format = BarcodeFormat.QR_CODE;
- write.Options = options;
- Bitmap bitmap = write.Write(content);
- IntPtr ip = bitmap.GetHbitmap();
- BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
- ip, IntPtr.Zero, Int32Rect.Empty,
- System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
- DeleteObject(ip);
- return bitmapSource;
- }
Copy code 5. Call createQRCode to complete the ImageSource generation of the QR code, and then use Image to display it.
|