有任何疑問請去個人新博客提出 https://blog.clso.fun/posts/2019-03-03/vb-net-zxing-net-qr-maker.htmlhtml
ZXing .NET 的項目主頁
https://github.com/micjahn/ZXing.Netgit
代碼基本上抄襲自下面兩篇文章 XD
http://www.cnblogs.com/tianma3798/p/5426869.html
http://www.cnblogs.com/tianma3798/p/5426880.htmlgithub
僅做參數優化,更加實用和簡便一點post
Shared Function MakeQR(ByVal qrtext As String, Optional ByVal width As Integer = 800, Optional ByVal height As Integer = 800, Optional ByVal margin As Integer = 1) As Bitmap Dim writer As New ZXing.BarcodeWriter writer.Format = ZXing.BarcodeFormat.QR_CODE Dim opt As New ZXing.QrCode.QrCodeEncodingOptions opt.DisableECI = True '設置爲True才能夠調整編碼 opt.CharacterSet = "UTF-8" '文本編碼,建議設置爲UTF-8 opt.Width = width '寬度 opt.Height = height '高度 opt.Margin = margin '邊距,貌似不是像素格式,所以不宜設置過大 writer.Options = opt Return writer.Write(qrtext) End Function Shared Function MakeQR(ByVal qrtext As String, ByVal logo As Bitmap, Optional ByVal width As Integer = 800, Optional ByVal height As Integer = 800, Optional ByVal margin As Integer = 1) As Bitmap If logo Is Nothing Then Return MakeQR(qrtext, width, height, margin) End If Dim writer As New ZXing.MultiFormatWriter Dim hint As New Dictionary(Of ZXing.EncodeHintType, Object)() hint.Add(ZXing.EncodeHintType.CHARACTER_SET, "UTF-8") hint.Add(ZXing.EncodeHintType.MARGIN, margin) hint.Add(ZXing.EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H) ' 生成二維碼 Dim bm As ZXing.Common.BitMatrix = writer.encode(qrtext, ZXing.BarcodeFormat.QR_CODE, width, height, hint) Dim barcodeWriter = New ZXing.BarcodeWriter() Dim bmp As Bitmap = barcodeWriter.Write(bm) '獲取二維碼實際尺寸(去掉二維碼兩邊空白後的實際尺寸) Dim rectangle As Integer() = bm.getEnclosingRectangle() '計算插入圖片的大小和位置 Dim middleW As Integer = Math.Min((rectangle(2) / 3.5), logo.Width) Dim middleH As Integer = Math.Min((rectangle(3) / 3.5), logo.Height) Dim middleL As Integer = (bmp.Width - middleW) / 2 Dim middleT As Integer = (bmp.Height - middleH) / 2 '將img轉換成bmp格式,不然後面沒法建立Graphics對象 Dim bmpimg As New Bitmap(bmp.Width, bmp.Height, Imaging.PixelFormat.Format32bppArgb) Using g As Graphics = Graphics.FromImage(bmpimg) g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality g.DrawImage(bmp, 0, 0) End Using '將二維碼插入圖片 Using myGraphic As Graphics = Graphics.FromImage(bmpimg) '白底 myGraphic.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH) myGraphic.DrawImage(logo, middleL, middleT, middleW, middleH) End Using bmp.Dispose() Return bmpimg End Function Shared Function ReadQR(ByVal bmp As Bitmap) As String Dim reader As New ZXing.BarcodeReader reader.Options.CharacterSet = "UTF-8" Dim ret As ZXing.Result = reader.Decode(bmp) If ret Is Nothing Then Return Nothing Else Return ret.Text End If End Function