golang中生成读取二维码(skip2/go-qrcode和boombuler/barcode,tuotoo/qrcode)

本文介绍了使用Golang中的skip2/go-qrcode、boombuler/barcode和tuotoo/qrcode库生成和解析二维码的方法。通过对比两种生成库,发现boombuler/barcode生成的二维码四周白边占比更小,效果更佳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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.youkuaiyun.com/wangshubo1989/article/details/77897363  

 

转载于:https://www.cnblogs.com/fanbi/p/10978675.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值