怎么用go语言编程实现二维码生成及识别

发布时间:2022-04-29 10:07:35 作者:iii
来源:亿速云 阅读:548

本文小编为大家详细介绍“怎么用go语言编程实现二维码生成及识别”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么用go语言编程实现二维码生成及识别”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

安装 go-qrcode

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

首先,我们安装我们用到的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的参数。

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

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

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语言编程实现二维码生成及识别”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. iOS 花式二维码生成和二维码识别
  2. 如何使用Go语言实现人脸识别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go语言

上一篇:vue3 $attrs和inheritAttrs怎么用

下一篇:Android怎么使用圆形揭露动画巧妙地隐藏或显示View

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》