Golang
主页 > 脚本 > Golang >

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/…

生成普通二维码

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

1

2

3

4

5

package main

import "github.com/skip2/go-qrcode"

func main() {

    qrcode.WriteFile("https://blog.csdn.net/yang731227",qrcode.Medium,256,"./qrcode.png")

}

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

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

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

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

1

2

3

4

5

6

7

8

9

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的值和透明值。

例如:

1

2

3

4

5

6

7

8

9

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")

}

识别二维码

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

首先我们安装库

1

go get github.com/tuotoo/qrcode

然后我们直接上代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

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)

}

原文链接:https://blog.csdn.net/yang731227/article/details/88542480
相关文章
最新更新