diff --git a/captcha.go b/captcha.go index 19ad554..da857b4 100644 --- a/captcha.go +++ b/captcha.go @@ -136,11 +136,7 @@ func New(width int, height int, option ...SetOption) (*Data, error) { text := randomText(options) 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(text, img, options) - if err != nil { + if err := drawWithOption(text, img, options); err != nil { return nil, err } @@ -157,11 +153,7 @@ func NewMathExpr(width int, height int, option ...SetOption) (*Data, error) { text, equation := randomEquation() 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(equation, img, options) - if err != nil { + if err := drawWithOption(equation, img, options); err != nil { return nil, err } @@ -179,17 +171,20 @@ func NewCustomGenerator( 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 { + if err := drawWithOption(question, img, options); err != nil { return nil, err } return &Data{Text: answer, img: img}, nil } +func drawWithOption(text string, img *image.NRGBA, options *Options) error { + draw.Draw(img, img.Bounds(), &image.Uniform{options.BackgroundColor}, image.Point{}, draw.Src) + drawNoise(img, options) + drawCurves(img, options) + return drawText(text, img, options) +} + func randomText(opts *Options) (text string) { n := len(opts.CharPreset) for i := 0; i < opts.TextLength; i++ { diff --git a/captcha_test.go b/captcha_test.go index c116c74..e75630e 100644 --- a/captcha_test.go +++ b/captcha_test.go @@ -69,6 +69,12 @@ func TestNewCaptchaOptions(t *testing.T) { NewMathExpr(100, 34, func(options *Options) { options.BackgroundColor = color.Black }) + + NewCustomGenerator(100, 34, func() (anwser string, question string) { + return "4", "2x2?" + }, func(o *Options) { + o.BackgroundColor = color.Black + }) } func TestNewMathExpr(t *testing.T) { @@ -101,6 +107,13 @@ func TestNilFontError(t *testing.T) { t.Fatal("Expect to get nil font error") } + _, err = NewCustomGenerator(150, 50, func() (anwser string, question string) { + return "1", "2" + }) + if err == nil { + t.Fatal("Expect to get nil font error") + } + ttfFont = temp }