new custom generator api

This commit is contained in:
Weilin Shi 2022-06-10 12:16:34 +08:00
parent 6aa88d953f
commit 20014aab1b
2 changed files with 31 additions and 0 deletions

View File

@ -168,6 +168,28 @@ func NewMathExpr(width int, height int, option ...SetOption) (*Data, error) {
return &Data{Text: text, img: img}, nil return &Data{Text: text, img: img}, nil
} }
// NewCustomGenerator creates a new captcha based on a custom text generator.
func NewCustomGenerator(
width int, height int, generator func() (anwser string, question string), option ...SetOption,
) (*Data, error) {
options := newDefaultOption(width, height)
for _, setOption := range option {
setOption(options)
}
answer, question := generator()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
draw.Draw(img, img.Bounds(), &image.Uniform{options.BackgroundColor}, image.Point{}, draw.Src)
drawNoise(img, options)
drawCurves(img, options)
err := drawText(question, img, options)
if err != nil {
return nil, err
}
return &Data{Text: answer, img: img}, nil
}
func randomText(opts *Options) (text string) { func randomText(opts *Options) (text string) {
n := len(opts.CharPreset) n := len(opts.CharPreset)
for i := 0; i < opts.TextLength; i++ { for i := 0; i < opts.TextLength; i++ {

View File

@ -78,6 +78,15 @@ func TestNewMathExpr(t *testing.T) {
} }
} }
func TestNewCustomGenerator(t *testing.T) {
_, err := NewCustomGenerator(150, 50, func() (anwser string, question string) {
return "1", "2"
})
if err != nil {
t.Fatal(err)
}
}
func TestNilFontError(t *testing.T) { func TestNilFontError(t *testing.T) {
temp := ttfFont temp := ttfFont
ttfFont = nil ttfFont = nil