2.23 Go之生成二维码
涉及到的第三方库
go-qrcode,该库的源代码托管在github上
调用函数
调用go-qrcode包下的WriteFile函数
函数:
func WriteFile(content string, level RecoveryLevel, size int, filename string) error
WriteFile函数参数:
- 
content表示要生成二维码的内容,可以是任意字符串;
- 
level表示二维码的容错级别,取值有Low、Medium、High、Highest;
- 
size表示生成图片的width和height,像素单位;
- 
filename表示生成的文件名路径;
- 
RecoveryLevel类型其实是个int,它的定义和常量如下:
type RecoveryLevel int
const (
    // Level L: 7% error recovery.
    Low RecoveryLevel = iota
    // Level M: 15% error recovery. Good default choice.
    Medium
    // Level Q: 25% error recovery.
    High
    // Level H: 30% error recovery.
    Highest
)
RecoveryLevel越高,二维码的容错能力越好
生成二维码图片字节
如果直接生成二维码那么图片格式是PNG格式,不方便对图片进行处理。此时可以使用Encode函数生成PNG图片的字节流。对字节流进行处理。
func Encode(content string, level RecoveryLevel, size int) ([]byte, error)
自定义二维码
go-qrcode库提供了对二维码的自定义方式,可以自定义二维码的前景色和背景色等。qrcode.New函数可以返回一个*QRCode,我们可以对*QRCode设置,实现对二维码的自定义。
示例代码:
package main
import (
    "github.com/skip2/go-qrcode"
    "image/color"
    "log"
)
/*
自定义一个二维码以及二维码内容
 */
func main() {
    qr, err := qrcode.New("https://www.cnblogs.com/JunkingBoy/", qrcode.Medium)
    if err != nil {
        log.Fatal(err)
    }else {
        qr.BackgroundColor = color.Black
        qr.ForegroundColor = color.White
        qr.WriteFile(256,"./学习资料.png")
    }
}
QRCode源码定义的结构体
func New(content string, level RecoveryLevel) (*QRCode, error)
// A QRCode represents a valid encoded QRCode.
type QRCode struct {
    // Original content encoded.
    Content string
    // QR Code type.
    Level         RecoveryLevel
    VersionNumber int
    // User settable drawing options.
    ForegroundColor color.Color
    BackgroundColor color.Color
}
/*
QRCode 的这些字段都是可以设置的
*/
注意:
二维码是一种流行的输入技术手段,不光 Go 可以生成,其他语言也可以生成,并且生成的二维码是标准的,都可以扫描和识别,比如 Java可以通过https://github.com/kenglxn/QRGen
    It's a lonely road!!!
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号