1. 程式人生 > >WPF調用zxing生成二維碼

WPF調用zxing生成二維碼

大小 pac xaml returns pri 進行 writer 創建 idt

1.登錄http://zxingnet.codeplex.com/,下載對應.net版本的zxing庫

2.引入zxing.dll

3.新建界面控件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using
System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ZXing.Common; using ZXing; using ZXing.QrCode; using System.Runtime.InteropServices; using System.Drawing; namespace zxingQRCodeDemo { /// <summary> /// MainWindow.xaml 的交互邏輯
/// </summary> public partial class MainWindow : Window { // 註銷對象方法API [DllImport("gdi32")] static extern int DeleteObject(IntPtr o); public MainWindow() { InitializeComponent(); } /// <summary> /// 創建二維碼圖像
/// </summary> /// <param name="content">要寫入的內容</param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> private ImageSource createQRCode(String content, int width, int height) { EncodingOptions options; //包含一些編碼、大小等的設置 //BarcodeWriter :一個智能類來編碼一些內容的條形碼圖像 BarcodeWriter write = null; 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();//從GDI+ Bitmap創建GDI位圖對象 //Imaging.CreateBitmapSourceFromHBitmap方法,基於所提供的非托管位圖和調色板信息的指針,返回一個托管的BitmapSource BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); DeleteObject(ip); return bitmapSource; } private void btnMake_Click(object sender, RoutedEventArgs e) { imQRCode.Source = createQRCode("牛逼不牛逼", 250, 250); } } }

WPF調用zxing生成二維碼