go语言编程二维码生成及识别

来自:网络
时间:2022-04-28
阅读:
目录

我们在做go web开发的时候,应该都遇到生成二维码分享的应用场景,下面我将介绍下使用go如何生成二维码。

安装 go-qrcode

我们不得不庆幸go的生态已经越来越丰富,有很多大牛已经帮我们写好了库,我们不必造轮子,直接拿过来用就好。

首先,我们安装我们用到的go-qrcode库。

https://github.com/skip2/go-qrcode/

go get -u github.com/skip2/go-qrcode/…

生成普通二维码

使用了这个库,你会发现二维码生成原来是如此的简单,现在我们就来演示一下。

package main
import "github.com/skip2/go-qrcode"
func main() {
	qrcode.WriteFile("https://blog.csdn.net/yang731227",qrcode.Medium,256,"./qrcode.png")
}

go语言编程二维码生成及识别

这样我们就可以生成了一个二维码。

我们首先看下func WriteFile(content string, level RecoveryLevel, size int, filename string) error的参数。

  • content string 简单明了,这个是二维码内容
  • level RecoveryLevel 这个是二维码容错等级,取值有Low、Medium、High、Highest。
  • size int 不用说都知道这个是定义二维码大小
  • filename string 二维码的保存路径

生成有前后背景颜色的二维码

刚刚我们生成了一个前黑后白的二维码,这次我们想搞点花样,生成一个花花绿绿的二维码,我们直接上代码

package main
import (
	"github.com/skip2/go-qrcode"
	"image/color"
)
func main() {
	//qrcode.WriteFile("https://blog.csdn.net/yang731227",qrcode.High,200,"./qrcode.png")
	qrcode.WriteColorFile("https://blog.csdn.net/yang731227", qrcode.High, 256, color.Black, color.White, "./qrcode.png")
}

我们来看下func WriteColorFile(content string, level RecoveryLevel, size int, background, foreground color.Color, filename string) error的参数,比WriteFile 多了两个参数 background, foreground color.Color 。我们可以从字面意思就知道,background 是背景颜色,foreground是前景颜色。

颜色我们可以使用 color定义 ,它为我们定义了两个默认颜色,Black和White。如果我们想用其他颜色怎么办呢?它为我们提供了color.RGBA() 这个方法,RGBA()有4个参数 分别是RGB的值和透明值。

例如:

package main
import (
	"github.com/skip2/go-qrcode"
	"image/color"
)
func main() {
	//qrcode.WriteFile("https://blog.csdn.net/yang731227",qrcode.High,200,"./qrcode.png")
	qrcode.WriteColorFile("https://blog.csdn.net/yang731227", qrcode.High, 256, color.Black, color.White, "./qrcode.png")
}

识别二维码

上面我们讲了怎么生成二维,现在我们来实习解析二维码,当然我们还是需要借助别人写的库。

首先我们安装库

go get github.com/tuotoo/qrcode

然后我们直接上代码

package main
import (
	"fmt"
	"os"
	"github.com/tuotoo/qrcode"
)
func main() {
	fi, err := os.Open("./qrcode.png")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer fi.Close()
	qrmatrix, err := qrcode.Decode(fi)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(qrmatrix.Content)
}

以上就是go语言编程二维码生成及识别的详细内容,更多关于go语言二维码生成识别的资料请关注其它相关文章!

返回顶部
顶部