golang中生成讀取二維碼(skip2/go-qrcode和boombuler/barcode,tuotoo/qrcode)

 1 引言git

在github上有好用golan二維碼生成和讀取庫,兩個生成二維碼的qrcode庫和一個讀取qrcode庫。github

skip2/go-qrcode生成二維碼,github地址:https://github.com/skip2/go-qrcode.net

boombuler/barcode生成二維碼,github地址:https://github.com/boombuler/barcode 
code

tuotoo/qrcode解析二維碼,github地址:https://github.com/tuotoo/qrcodeblog

 

2 代碼圖片

import (
   "image/png"
   "os"
   "github.com/boombuler/barcode"
   "github.com/boombuler/barcode/qr"
   "github.com/skip2/go-qrcode"
   qrcodeReader "github.com/tuotoo/qrcode"
   "fmt"
)

func main() {

   content := "https://www.cnblogs.com/fanbi"
   size := 200

   //Skip2
   dest := "qrcode.png"
   CreateQRCodeBySkip2(content, qrcode.Medium, size, dest)
   fmt.Println("QRCodeBySkip2 content",ReadQRCode(dest))

   //Boombuler
   dest2 := "qrcode2.png"
   CreateQRCodeByBoombuler(content, qr.M, size, dest2)
   fmt.Println("QRCodeBySBoombule content",ReadQRCode(dest2))

   //輸出
   //QRCodeBySkip2 content https://www.cnblogs.com/fanbi
   //QRCodeBySBoombule content https://www.cnblogs.com/fanbi

}

func CreateQRCodeBySkip2(content string, quality qrcode.RecoveryLevel, size int, dest string) (err error) {
   err = qrcode.WriteFile(content, quality, size, dest)
   return
}

func CreateQRCodeByBoombuler(content string, quality qr.ErrorCorrectionLevel, size int, dest string) (err error) {
   qrCode, err := qr.Encode(content, quality, qr.Auto)
   if err != nil {
      return
   }

   // Scale the barcode to 200x200 pixels
   qrCode, err = barcode.Scale(qrCode, size, size)
   if err != nil {
      return
   }

   // create the output file
   file, err := os.Create(dest)
   if err != nil {
      return
   }

   defer file.Close()
   // encode the barcode as png
   err = png.Encode(file, qrCode)
   if err != nil {
      return
   }

   return
}

func ReadQRCode(filename string) (content string) {
   fi, err := os.Open(filename)
   if err != nil {
      fmt.Println(err.Error())
      return
   }
   defer fi.Close()
   qrmatrix, err := qrcodeReader.Decode(fi)
   if err != nil {
      fmt.Println(err.Error())
      return
   }
   return qrmatrix.Content
}

效果圖:ip

qrcode.png

qrcode2.png

 說明:第二種生成的二維碼會更好,圖片的四周白邊佔比小。get

 

3 參考string

https://blog.csdn.net/wangshubo1989/article/details/77897363  it

相關文章
相關標籤/搜索