2017-09-16 11:04:28 +01:00
|
|
|
package captcha
|
|
|
|
|
|
|
|
import (
|
|
|
|
"image"
|
2017-09-17 07:50:28 +01:00
|
|
|
"image/color"
|
2017-09-16 11:04:28 +01:00
|
|
|
"image/png"
|
2017-09-17 07:50:28 +01:00
|
|
|
"io"
|
2017-09-16 11:04:28 +01:00
|
|
|
"math/rand"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
|
|
|
|
|
|
type Options struct {
|
|
|
|
BackgroundColor color.RGBA
|
2017-09-17 07:50:28 +01:00
|
|
|
CharPreset string
|
|
|
|
TxtLength int
|
|
|
|
width int
|
|
|
|
height int
|
2017-09-16 11:04:28 +01:00
|
|
|
}
|
|
|
|
|
2017-09-17 07:50:28 +01:00
|
|
|
func newDefaultOption(width, height int) *Options {
|
2017-09-16 11:04:28 +01:00
|
|
|
return &Options{
|
|
|
|
CharPreset: charPreset,
|
2017-09-17 07:50:28 +01:00
|
|
|
TxtLength: 4,
|
|
|
|
width: width,
|
|
|
|
height: height,
|
2017-09-16 11:04:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type Option func(*Options)
|
|
|
|
|
|
|
|
type Data struct {
|
|
|
|
Text string
|
|
|
|
|
|
|
|
img *image.NRGBA
|
|
|
|
}
|
|
|
|
|
|
|
|
func (data *Data) WriteTo(w io.Writer) error {
|
|
|
|
return png.Encode(w, data.img)
|
|
|
|
}
|
|
|
|
|
2017-09-17 07:50:28 +01:00
|
|
|
func New(width int, height int, option ...Option) *Data {
|
|
|
|
options := newDefaultOption(width, height)
|
2017-09-16 11:04:28 +01:00
|
|
|
for _, setOption := range option {
|
|
|
|
setOption(options)
|
|
|
|
}
|
|
|
|
|
|
|
|
text := randomText(options)
|
|
|
|
img := image.NewNRGBA(image.Rect(0, 0, width, height))
|
2017-09-17 07:50:28 +01:00
|
|
|
drawNoise(img, options)
|
2017-09-16 11:04:28 +01:00
|
|
|
|
|
|
|
return &Data{Text: text, img: img}
|
|
|
|
}
|
|
|
|
|
|
|
|
func randomText(opts *Options) (text string) {
|
|
|
|
n := len(opts.CharPreset)
|
2017-09-17 07:50:28 +01:00
|
|
|
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
|
|
for i := 0; i < opts.TxtLength; i++ {
|
|
|
|
text += string(opts.CharPreset[rng.Intn(n)])
|
2017-09-16 11:04:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return text
|
|
|
|
}
|
2017-09-17 07:50:28 +01:00
|
|
|
|
|
|
|
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)}
|
|
|
|
}
|