add: draw noise

This commit is contained in:
Weilin 2017-09-17 14:50:28 +08:00
parent 95aa54b0c3
commit cd62640c27
1 changed files with 35 additions and 11 deletions

View File

@ -1,10 +1,10 @@
package captcha package captcha
import ( import (
"io"
"image/color"
"image" "image"
"image/color"
"image/png" "image/png"
"io"
"math/rand" "math/rand"
"time" "time"
) )
@ -13,14 +13,18 @@ const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567
type Options struct { type Options struct {
BackgroundColor color.RGBA BackgroundColor color.RGBA
CharPreset string CharPreset string
TxtLength int TxtLength int
width int
height int
} }
func newDefaultOption() *Options { func newDefaultOption(width, height int) *Options {
return &Options{ return &Options{
CharPreset: charPreset, CharPreset: charPreset,
TxtLength: 4, TxtLength: 4,
width: width,
height: height,
} }
} }
@ -36,24 +40,44 @@ func (data *Data) WriteTo(w io.Writer) error {
return png.Encode(w, data.img) return png.Encode(w, data.img)
} }
func New(width int, height int, option... Option) *Data { func New(width int, height int, option ...Option) *Data {
options := newDefaultOption() options := newDefaultOption(width, height)
for _, setOption := range option { for _, setOption := range option {
setOption(options) setOption(options)
} }
text := randomText(options) text := randomText(options)
img := image.NewNRGBA(image.Rect(0, 0, width, height)) img := image.NewNRGBA(image.Rect(0, 0, width, height))
drawNoise(img, options)
return &Data{Text: text, img: img} return &Data{Text: text, img: img}
} }
func randomText(opts *Options) (text string) { func randomText(opts *Options) (text string) {
n := len(opts.CharPreset) n := len(opts.CharPreset)
r := rand.New(rand.NewSource(time.Now().UnixNano())) rng := rand.New(rand.NewSource(time.Now().UnixNano()))
for i :=0; i < opts.TxtLength; i++ { for i := 0; i < opts.TxtLength; i++ {
text += string(opts.CharPreset[r.Intn(n)]) text += string(opts.CharPreset[rng.Intn(n)])
} }
return text return text
} }
func drawNoise(img *image.NRGBA, opts *Options) {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
noiseCount := (opts.width * opts.height) / 18
for i := 0; i < noiseCount; i++ {
x := rng.Intn(opts.width)
y := rng.Intn(opts.height)
img.Set(x, y, randomColor())
}
}
func randomColor() color.RGBA {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
red := rng.Intn(255)
green := rng.Intn(255)
blue := rng.Intn(255)
return color.RGBA{R: uint8(red), G: uint8(green), B: uint8(blue), A: uint8(255)}
}