base64 golang 图片_gin生成base64的验证码图片

本文介绍了如何在Golang中利用base64Captcha库生成base64编码的验证码图片,包括下载第三方库、设置CaptchaConfig类、创建实例、实现API接口以及验证码验证的方法。此外,还提到了base64Captcha库中的不同验证码类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一步 下载第三方组件

go get -u github.com/mojocn/base64Captcha

下载过程中可能出错,主要原因还是go get golang.org/x/image 失败

解决方法:①cd $GOPATH/src/golang.org/x

② git clone https://github.com/golang/image

第二歩 设置CaptchaConfig类

type CaptchaConfig struct {

Id string

CaptchaType string

VerifyValue string

ConfigAudio base64Captcha.ConfigAudio

ConfigCharacter base64Captcha.ConfigCharacter

ConfigDigit base64Captcha.ConfigDigit

}

第三歩 创建CaptchaConfig类实例

var (

captchaConfig *CaptchaConfig

captchaConfigOnce sync.Once

)

// 获取base64验证码基本配置

func GetCaptchaConfig() *CaptchaConfig {

captchaConfigOnce.Do(func() {

captchaConfig = &CaptchaConfig{

Id: "",

CaptchaType: "character",

VerifyValue: "",

ConfigAudio: base64Captcha.ConfigAudio{},

ConfigCharacter: base64Captcha.ConfigCharacter{

Height: 60,

Width: 240,

Mode: 2,

IsUseSimpleFont: false,

ComplexOfNoiseText: 0,

ComplexOfNoiseDot: 0,

IsShowHollowLine: false,

IsShowNoiseDot: false,

IsShowNoiseText: false,

IsShowSlimeLine: false,

IsShowSineLine: false,

CaptchaLen: 0,

},

ConfigDigit: base64Captcha.ConfigDigit{},

}

})

return captchaConfig

}

第四歩 API部分

const (

CAPTCHA_IS_RIGHT = 0

CAPTCHA_IS_ERROR = -7

)

func GenerateCaptchaHandler(c *gin.Context) {

// get session

session := sessions.Default(c)

captchaConfig := util.GetCaptchaConfig()

//create base64 encoding captcha

//创建base64图像验证码

config := captchaConfig.ConfigCharacter

//GenerateCaptcha 第一个参数为空字符串,包会自动在服务器一个随机种子给你产生随机uiid.

captchaId, digitCap := base64Captcha.GenerateCaptcha(captchaConfig.Id, config)

base64Png := base64Captcha.CaptchaWriteToBase64Encoding(digitCap)

session.Set("captchaId", captchaId)

c.String(http.StatusOK, base64Png)

}

// 验证 验证码是否正确

// captchaId: 存于session中

// verifyValue: 客户端发来的验证码

func VerfiyCaptcha(captchaId, verifyValue string) (int, error){

verifyResult := base64Captcha.VerifyCaptcha(captchaId, verifyValue)

if verifyResult {

return CAPTCHA_IS_RIGHT,nil

} else {

return CAPTCHA_IS_ERROR, fmt.Errorf("captcha is error")

}

}

第五歩 简单介绍base64Captcha库的一些变量,参数

CaptchaModeNumber:数字,

CaptchaModeAlphabet:字母,

CaptchaModeArithmetic:算术,

CaptchaModeNumberAlphabet:数字字母混合.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值