go生成图片验证码-base64Captcha库的使用

724 阅读2分钟

本文主要介绍如何使用base64Captcha库生成图片验证码

1.安装

go get -u github.com/mojocn/base64Captcha

2.使用方法

2.1 设置store(使用内存方式)

声明store,使用默认配置

var store = base64Captcha.DefaultMemStore

DefaultMemStore配置如下

// GCLimitNumber 生成的验证码数量,用于触发默认存储空间的垃圾回收
GCLimitNumber = 10240
// Expiration 验证码过期时间
Expiration = 10 * time.Minute
// DefaultMemStore is a shared storage for captchas, generated by New function.
DefaultMemStore = NewMemoryStore(GCLimitNumber, Expiration)

也可以使用NewMemoryStore()自定义store

var store = base64Captcha.NewMemoryStore(GCLimitNumber, Expiration)

2.2 设置Driver

Driver一共有以下几种:

image.png

这里以DriverString(生成字符验证码)为例。DriverString配置如下:

type DriverString struct {
    // Height png height in pixel.
    Height int

    // Width Captcha png width in pixel.
    Width int

    //NoiseCount text noise count.
    NoiseCount int

    //ShowLineOptions := OptionShowHollowLine | OptionShowSlimeLine | OptionShowSineLine .
    ShowLineOptions int

    //Length random string length.
    Length int

    //Source is a unicode which is the rand string from.
    Source string

    //BgColor captcha image background color (optional)
    BgColor *color.RGBA

    //fontsStorage font storage (optional)
    fontsStorage FontsStorage

    //Fonts loads by name see fonts.go's comment
    Fonts      []string
    fontsArray []*truetype.Font
}

配置 Driver

driverStringConfig := &base64Captcha.DriverString{
    // 验证码图片的高度
    Height: 50,
    // 验证码图片的宽度
    Width: 120,
    // 验证码图片中随机噪点的数量
    NoiseCount: 2,
    // 控制显示在验证码图片中的线条的选项
    ShowLineOptions: 2 | 4,
    // 验证码的长度,即验证码中字符的数量
    Length: 4,
    // 验证码的字符源,用于生成验证码的字符。在这个例子中,使用数字和小写字母作为字符源
    Source: "1234567890abcdefghijklmnopqrstuvwxyz",
    BgColor: &color.RGBA{
       //验证码图片的背景颜色
       R: 100,
       G: 200,
       B: 100,
       A: 125,
    },
    //用于绘制验证码文本的字体文件。使用"wqy-microhei.ttc"的字体文件
    Fonts: []string{"wqy-microhei.ttc"},
}

// 将driverString中指定的字体文件转换为驱动程序所需的字体格式,这个步骤是为了将字体文件转换为正确的格式,以便在生成验证码时使用正确的字体
driver := driverStringConfig.ConvertFonts()

2.3 生成验证码图片

// 实例化一个captcha结构体
cap := captcha.NewCaptcha(driver, store)
// 生成id,content,answer
id, content, answer := cap.Driver.GenerateIdQuestionAnswer()
// 将answer存到内存中
err := cap.Store.Set(id, answer)
// 处理 err
...
// 生成图片
item, err:= cap.Driver.DrawCaptcha(content)
// 处理 err
...
// 转为base64编码string格式
b64s := item.EncodeB64string()

也可以直接使用 Generate() 方法

cap = captcha.NewCaptcha(driver, store)
id, b64s, answer, err := cap.Generate()

2.4 验证验证码

// 两种方式
ok := store.Verify(id, answer, true)

ok := cap.Verify(id, answer, true)