1.效果圖
2.BarcodeWriter 用於生成圖片格式的條碼類,通過Write函數進行輸出。
BarcodeFormat 枚舉類型,條碼格式。
EncodingOptions,主要設置寬,高,編碼方式等信息。
BitMatrix 表示按位表示的二維矩陣數組,元素的值用true和false表示二進制中的1和0。
/ 生成二維碼 private System.Drawing.Image GeneratorQR(string msg) { var QRmsg = "https://www.baidu.com/"; if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\\")) { Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\\"); } var QRpath = System.AppDomain.CurrentDomain.BaseDirectory + "QRBar1\\" + "QrCode" + ".jpg"; // MessageBox.Show(QRpath); BarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.QR_CODE }; writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8"); // 編碼問題 writer.Options.Hints.Add(EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H); int codeSizeInPixels = 150; // 設置圖片長寬 writer.Options.Height = 150; writer.Options.Width = 150; writer.Options.Margin = 0; // 設置邊框 BitMatrix bm = writer.Encode(msg); Bitmap img = writer.Write(bm); img.Save(@QRpath); imageQR.Source = BitmapToBitmapImage(img); return img; }
3.
Bitmap 轉換為 BitmapImage(避免圖片被占用,我之前的博客有提到過)
// Bitmap --> BitmapImage public static BitmapImage BitmapToBitmapImage(Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Png); stream.Position = 0; BitmapImage result = new BitmapImage(); result.BeginInit(); result.CacheOption = BitmapCacheOption.OnLoad; result.StreamSource = stream; result.EndInit(); result.Freeze(); return result; } }
4.源碼下載。
https://files-cdn.cnblogs.com/files/king10086/QR.7z