怎么用go语言编程实现二维码生成及识别
导读:本文共1954.5字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 安装 go-qrcode我们不得不庆幸go的生态已经越来越丰富,有很多大牛已经帮我们写好了库,我们不必造轮子,直接拿过来用就好。首先,我们安装我们用到的go-qrcode库。go get -u github.com/skip2/go-qrcode/…生成普通二维码使用了这个库,你会发现二维码生成原来是如此的简单,现在我们就来演示一下。pac... ...
目录
(为您整理了一些要点),点击可以直达。安装 go-qrcode
我们不得不庆幸go的生态已经越来越丰富,有很多大牛已经帮我们写好了库,我们不必造轮子,直接拿过来用就好。
首先,我们安装我们用到的go-qrcode
库。
go get -u github.com/skip2/go-qrcode/…
生成普通二维码
使用了这个库,你会发现二维码生成原来是如此的简单,现在我们就来演示一下。
packagemainimport"github.com/skip2/go-qrcode"funcmain(){ qrcode.WriteFile("https://blog.csdn.net/yang731227",qrcode.Medium,256,"./qrcode.png")}
这样我们就可以生成了一个二维码。
我们首先看下func WriteFile(content string, level RecoveryLevel, size int, filename string) error的参数。
content string 简单明了,这个是二维码内容
level RecoveryLevel 这个是二维码容错等级,取值有Low、Medium、High、Highest。
size int 不用说都知道这个是定义二维码大小
filename string 二维码的保存路径
生成有前后背景颜色的二维码
刚刚我们生成了一个前黑后白的二维码,这次我们想搞点花样,生成一个花花绿绿的二维码,我们直接上代码
packagemainimport( "github.com/skip2/go-qrcode" "image/color")funcmain(){ //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的值和透明值。
例如:
packagemainimport( "github.com/skip2/go-qrcode" "image/color")funcmain(){ //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")}
识别二维码
上面我们讲了怎么生成二维,现在我们来实习解析二维码,当然我们还是需要借助别人写的库。
首先我们安装库
gogetgithub.com/tuotoo/qrcode
然后我们直接上代码
packagemainimport( "fmt" "os" "github.com/tuotoo/qrcode")funcmain(){ fi,err:=os.Open("./qrcode.png") iferr!=nil{ fmt.Println(err.Error()) return } deferfi.Close() qrmatrix,err:=qrcode.Decode(fi) iferr!=nil{ fmt.Println(err.Error()) return } fmt.Println(qrmatrix.Content)}
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
怎么用go语言编程实现二维码生成及识别的详细内容,希望对您有所帮助,信息来源于网络。