使用ZXing.dll庫生成二維碼(C#實現)

最近工做中有須要一個需求,就是把一個服務地址生成二維碼,能夠用來掃碼分享,網上找了下方法也比較多,我這裏po一下調用ZXing.dll庫生成二維碼的方法吧。先簡單介紹一下 ZXing庫,ZXing庫是一個開源Java類庫,可用於生成和解析多種格式的1D/2D條形碼;zxing遵循Apache License 2.0,只是工具而已,是不收費噠。工具

ZXing庫的下載地址:http://zxingnet.codeplex.com/spa

點擊下載下載後解壓壓縮包:code

把Zxing加到工程應用中,如下爲核心代碼:orm

 1 /// <summary>
 2         /// 生成二維碼圖片
 3         /// </summary>
 4         /// <param name="strMessage">要生成二維碼的字符串</param>
 5         /// <param name="width">二維碼圖片寬度</param>
 6         /// <param name="height">二維碼圖片高度</param>
 7         /// <returns></returns>
 8         private Bitmap GetQRCodeByZXingNet(String strMessage,Int32 width,Int32 height)
 9         {
10             Bitmap result = null;
11             try
12             {
13                 BarcodeWriter barCodeWriter = new BarcodeWriter();
14                 barCodeWriter.Format = BarcodeFormat.QR_CODE;
15                 barCodeWriter.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
16                 barCodeWriter.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H);
17                 barCodeWriter.Options.Height = height;
18                 barCodeWriter.Options.Width = width;
19                 barCodeWriter.Options.Margin = 0;
20                 ZXing.Common.BitMatrix bm = barCodeWriter.Encode(strMessage);
21                 result = barCodeWriter.Write(bm);
22             }
23             catch (Exception ex)
24             { 
25                 //異常輸出
26             }
27             return result;
28         }

看一下生成二維碼的效果:blog

 

同時  Zxing庫也支持對二維碼圖片解碼圖片

解碼的核心代碼以下:字符串

/// <summary>
        /// 解碼二維碼
        /// </summary>
        /// <param name="barcodeBitmap">待解碼的二維碼圖片</param>
        /// <returns>掃碼結果</returns>
        private string DecodeQrCode(Bitmap barcodeBitmap)
        {
             BarcodeReader reader = new BarcodeReader();
             reader.Options.CharacterSet = "UTF-8";
             var result = reader.Decode(barcodeBitmap);
             return (result == null) ? null : result.Text;
        }

看一下效果:get

隨便找了個二維碼:string

掃碼結果以下:it

相關文章
相關標籤/搜索