add: NewMathExpr API

This commit is contained in:
Weilin Shi 2017-09-28 08:18:29 +08:00
parent 551c5cd7fb
commit f9832124ae
2 changed files with 39 additions and 2 deletions

View File

@ -103,6 +103,27 @@ func New(width int, height int, option ...SetOption) (*Data, error) {
return &Data{Text: text, img: img}, nil return &Data{Text: text, img: img}, nil
} }
// NewMathExpr creates a new captcha.
// It will generate a image with a math expression like `1 + 2`
func NewMathExpr(width int, height int, option ...SetOption) (*Data, error) {
options := newDefaultOption(width, height)
for _, setOption := range option {
setOption(options)
}
text, equation := randomEquation()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
draw.Draw(img, img.Bounds(), &image.Uniform{options.BackgroundColor}, image.ZP, draw.Src)
drawNoise(img, options)
drawCurves(img, options)
err := drawText(equation, img, options)
if err != nil {
return nil, err
}
return &Data{Text: text, 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++ {
@ -183,7 +204,7 @@ func drawText(text string, img *image.NRGBA, opts *Options) error {
fontScale := 1 + rng.Float64()*0.5 fontScale := 1 + rng.Float64()*0.5
fontSize := float64(opts.height) / fontScale fontSize := float64(opts.height) / fontScale
ctx.SetFontSize(fontSize) ctx.SetFontSize(fontSize)
ctx.SetSrc(image.NewUniform(randomDarkColor())) ctx.SetSrc(image.NewUniform(randomInvertColor(opts.BackgroundColor)))
x := fontSpacing*idx + fontSpacing/int(fontSize) x := fontSpacing*idx + fontSpacing/int(fontSize)
y := opts.height/6 + rng.Intn(opts.height/3) + int(fontSize/2) y := opts.height/6 + rng.Intn(opts.height/3) + int(fontSize/2)
pt := freetype.Pt(x, y) pt := freetype.Pt(x, y)

View File

@ -4,8 +4,8 @@ import (
"bytes" "bytes"
"golang.org/x/image/font/gofont/goregular" "golang.org/x/image/font/gofont/goregular"
"image/color" "image/color"
"testing"
"math/rand" "math/rand"
"testing"
) )
func TestNewCaptcha(t *testing.T) { func TestNewCaptcha(t *testing.T) {
@ -31,6 +31,17 @@ func TestNewCaptchaOptions(t *testing.T) {
options.CurveNumber = 0 options.CurveNumber = 0
options.TextLength = 6 options.TextLength = 6
}) })
NewMathExpr(100, 34, func(options *Options) {
options.BackgroundColor = color.Black
})
}
func TestNewMathExpr(t *testing.T) {
_, err := NewMathExpr(150, 50)
if err != nil {
t.Fatal(err)
}
} }
func TestCovNilFontError(t *testing.T) { func TestCovNilFontError(t *testing.T) {
@ -42,6 +53,11 @@ func TestCovNilFontError(t *testing.T) {
t.Fatal("Expect to get nil font error") t.Fatal("Expect to get nil font error")
} }
_, err = NewMathExpr(150, 50)
if err == nil {
t.Fatal("Expect to get nil font error")
}
ttfFont = temp ttfFont = temp
} }