编辑
2023-09-21
后端
00
请注意,本文编写于 597 天前,最后修改于 597 天前,其中某些信息可能已经过时。

接下来是一个用github.com/afocus/captcha库生成验证码的示例

go
package main import ( "image/color" "image/png" "net/http" "github.com/afocus/captcha" ) var cap *captcha.Captcha func main() { cap = captcha.New() if err := cap.SetFont("comic.ttf"); err != nil { panic(err.Error()) } /* //We can load font not only from localfile, but also from any []byte slice fontContenrs, err := ioutil.ReadFile("comic.ttf") if err != nil { panic(err.Error()) } err = cap.AddFontFromBytes(fontContenrs) if err != nil { panic(err.Error()) } */ cap.SetSize(150, 100) cap.SetDisturbance(captcha.HIGH) cap.SetFrontColor(color.RGBA{255, 255, 255, 255}) cap.SetBkgColor(color.RGBA{255, 0, 0, 255}, color.RGBA{0, 0, 255, 255}, color.RGBA{0, 153, 0, 255}) http.HandleFunc("/r", func(w http.ResponseWriter, r *http.Request) { img, str := cap.Create(6, captcha.ALL) png.Encode(w, img) println(str) }) http.HandleFunc("/c", func(w http.ResponseWriter, r *http.Request) { str := r.URL.RawQuery img := cap.CreateCustom(str) png.Encode(w, img) }) http.ListenAndServe(":8085", nil) }

除却这些代码,还需要包含特定字体

image.png 包含字体的.ttf文件,切记,这个库大小超过150 x 150,生成的验证码会出现不可识别的情况,所以适合生成小型验证码需求

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!