package captcha import ( "image" "os" "path/filepath" "picgo/configs" "picgo/corelib" "strings" ) // GenerateCaptcha 图形验证码 func GenerateCaptcha(cid string) (img *image.RGBA, err error) { // 字体路径 dir, err := os.Getwd() if err != nil { return } var fontPath = filepath.Join(dir, "corelib", "captcha", "fonts") // 随机字体 var fontNames = []string{"DENNEthree-dee", "3Dumb"} fontName := RandChooseOne(fontNames) // 随机模式 var modes = []int{0, 1} mode := RandChooseOne(modes) // 生成图片验证码 captchaLen := configs.Settings.Captcha.Length w := configs.Settings.Captcha.Width h := configs.Settings.Captcha.Hight cp := NewCaptcha(w, h, captchaLen) cp.SetFontPath(fontPath) //指定字体目录 cp.SetFontName(fontName) //指定字体名字 cp.SetMode(mode) //1:设置为简单的数学算术运算公式; 其他为普通字符串 code, img := cp.OutPut() // 备注:code 存储到redis,并在使用时取出验证 corelib.Logger.Infoln("图片验证码: ", code) // 配置文件中获取过期时间 exp := configs.Settings.Captcha.Expire // 缓存生成的验证码 if err = SetCode(cid, code, int64(exp)); err != nil { return } //core.Logger.Infoln("验证结果:", Verify(cid, code)) return } // Verify 验证 func Verify(id string, code string) (ok bool) { ok = false var ( err error redisCode string ) // 验证字符串是否合法 if code == "" || !corelib.IsCaptcha(code) { return } code = strings.ToLower(code) // redis取验证码 if redisCode, err = GetCode(id); err != nil { return } // redis存储验证码和用户输入验证码对比 if strings.ToLower(redisCode) == code { return true } return }