WPF 創建二維碼
1.在http://zxingnet.codeplex.com/站點上下載ZXing .Net的第三方庫
2.新建一個WPF工程
3.引入zxing.dll
4.添加引用空間
using ZXing.Common;
using ZXing;
using ZXing.QrCode;
5.添加引用System.Drawing
6.添加引用空間
using System.Drawing;
7.在xaml中添加一個Image控件,用于顯示二維碼,命名為image1.
8.編寫生成二維碼函數:
// 注銷對象方法API
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
/ 創建二維碼圖片 /
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;
}
9.在xaml中添加一個button,并為button添加click事件
10.在button的click事件中調用生成二維碼的函數:
image1.Source = createQRCode("牛逼",250, 250);
11.運行程序,Image控件中顯示生成的二維碼,用手機掃描,可以得到二維碼的內容“牛逼”。