zoukankan      html  css  js  c++  java
  • golang中生成读取二维码(skip2/go-qrcode和boombuler/barcode,tuotoo/qrcode)

     1 引言

    在github上有好用golan二维码生成和读取库,两个生成二维码的qrcode库和一个读取qrcode库。

    skip2/go-qrcode生成二维码,github地址:https://github.com/skip2/go-qrcode

    boombuler/barcode生成二维码,github地址:https://github.com/boombuler/barcode 

    tuotoo/qrcode解析二维码,github地址:https://github.com/tuotoo/qrcode

    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
    }

    效果图:

    qrcode.png

    qrcode2.png

     说明:第二种生成的二维码会更好,图片的四周白边占比小。

    3 参考

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

  • 相关阅读:
    团队总结-文艺复兴
    文艺复兴-冲刺总结
    文艺复习-测试博客
    文艺复习-冲刺集合
    冲刺第一天
    凡事预则立
    2020软件工程作业05
    2020软件工程作业04
    前端怎么去学
    十、Kernel_3.0.35版本和Kernel_4.1.15版本在SPI驱动实现机制的差异
  • 原文地址:https://www.cnblogs.com/fanbi/p/10978675.html
Copyright © 2011-2022 走看看