-
Notifications
You must be signed in to change notification settings - Fork 0
/
captcha.go
340 lines (280 loc) · 8.32 KB
/
captcha.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Package provides an simple, unopinionated API for captcha generation
package captcha
import (
_ "embed"
"image"
"image/color"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"math"
"math/rand"
"strconv"
"time"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
)
const charPreset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var (
//go:embed fonts/Comismsh.ttf
ttf []byte
ttfFont *truetype.Font
)
// Options manage captcha generation.
type Options struct {
// BackgroundColor is captcha image's background color.
// By default it is color.Transparent.
BackgroundColor color.Color
// CharPreset defines the text on the captcha image.
// By default:
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
CharPreset string
// TextLength is the length of the captcha text.
// By default it is 4.
TextLength int
// CurveNumber is the number of curves to draw on captcha image.
// By default it is 2.
CurveNumber int
// FontDPI controls DPI (dots per inch) of font.
// By default it is 72.0.
FontDPI float64
// FontScale controls the scale of font.
// By default it is 1.0.
FontScale float64
// Noise controls the amount of noise to be drawn.
// By default, a noise point is drawn every 28 pixels.
// By default it is 1.0.
Noise float64
// Palette is the set of colors to chose from.
Palette color.Palette
width int
height int
}
// Captcha is the result of captcha generation.
// It has a `Text` field and a private `img` field,
// which will be used in the `WriteImage` receiver.
type Captcha struct {
Text string
img *image.NRGBA
}
// SetOption is a function used to change the default settings.
type SetOption func(*Options)
func init() {
ttfFont, _ = freetype.ParseFont(ttf)
rand.Seed(time.Now().UnixNano())
}
func newDefaultOption(width, height int) *Options {
return &Options{
BackgroundColor: color.Transparent,
CharPreset: charPreset,
TextLength: 4,
CurveNumber: 2,
FontDPI: 72.0,
FontScale: 1.0,
Noise: 1.0,
Palette: []color.Color{},
width: width,
height: height,
}
}
// New creates a new captcha.
func New(width int, height int, option ...SetOption) (*Captcha, error) {
options := newDefaultOption(width, height)
for _, setOption := range option {
setOption(options)
}
text := randomText(options)
img := image.NewNRGBA(image.Rect(0, 0, width, height))
if err := drawWithOption(text, img, options); err != nil {
return nil, err
}
return &Captcha{Text: text, img: img}, nil
}
// NewMathExpr creates a new captcha.
// Generates an image with a mathematical expression like `1 + 2`.
func NewMathExpr(width int, height int, option ...SetOption) (*Captcha, error) {
options := newDefaultOption(width, height)
for _, setOption := range option {
setOption(options)
}
text, equation := randomEquation()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
if err := drawWithOption(equation, img, options); err != nil {
return nil, err
}
return &Captcha{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) (*Captcha, error) {
options := newDefaultOption(width, height)
for _, setOption := range option {
setOption(options)
}
answer, question := generator()
img := image.NewNRGBA(image.Rect(0, 0, width, height))
if err := drawWithOption(question, img, options); err != nil {
return nil, err
}
return &Captcha{Text: answer, img: img}, nil
}
// WriteImage encodes image data and writes it to io.Writer.
// Returns an error possible when encoding PNG.
func (c *Captcha) WriteImage(w io.Writer) error {
return png.Encode(w, c.img)
}
// WriteJPG encodes the image data into JPEG format and writes it to io.Writer.
// Returns an error possible when encoding JPEG.
func (c *Captcha) WriteJPG(w io.Writer, o *jpeg.Options) error {
return jpeg.Encode(w, c.img, o)
}
// WriteGIF encodes the image data into GIF format and writes it to io.Writer.
// Returns an error possible when encoding GIF.
func (c *Captcha) WriteGIF(w io.Writer, o *gif.Options) error {
return gif.Encode(w, c.img, o)
}
// LoadFont lets load an external font.
func LoadFont(fontData []byte) (err error) {
ttfFont, err = freetype.ParseFont(fontData)
return err
}
// LoadFontFromReader load an external font from an io.Reader interface.
func LoadFontFromReader(reader io.Reader) error {
b, err := io.ReadAll(reader)
if err != nil {
return err
}
return LoadFont(b)
}
func randomText(opts *Options) (text string) {
n := len([]rune(opts.CharPreset))
for i := 0; i < opts.TextLength; i++ {
text += string([]rune(opts.CharPreset)[rand.Intn(n)])
}
return text
}
func randomColor() color.RGBA {
red := rand.Intn(256)
green := rand.Intn(256)
blue := rand.Intn(256)
return color.RGBA{R: uint8(red), G: uint8(green), B: uint8(blue), A: uint8(255)}
}
func randomColorFromOptions(opts *Options) color.Color {
length := len(opts.Palette)
if length == 0 {
return randomInvertColor(opts.BackgroundColor)
}
return opts.Palette[rand.Intn(length)]
}
func randomEquation() (text string, equation string) {
left := 1 + rand.Intn(9)
right := 1 + rand.Intn(9)
text = strconv.Itoa(left + right)
equation = strconv.Itoa(left) + "+" + strconv.Itoa(right)
return text, equation
}
func randomInvertColor(base color.Color) color.Color {
var value float64
baseLightness := getLightness(base)
if baseLightness >= 0.5 {
value = baseLightness - 0.3 - rand.Float64()*0.2
} else {
value = baseLightness + 0.3 + rand.Float64()*0.2
}
hue := float64(rand.Intn(361)) / 360
saturation := 0.6 + rand.Float64()*0.2
return hsva{h: hue, s: saturation, v: value, a: 255}
}
func maxColor(numList ...uint32) (max uint32) {
for _, num := range numList {
colorVal := num & 255
if colorVal > max {
max = colorVal
}
}
return max
}
func minColor(numList ...uint32) (min uint32) {
min = 255
for _, num := range numList {
colorVal := num & 255
if colorVal < min {
min = colorVal
}
}
return min
}
func getLightness(colour color.Color) float64 {
r, g, b, a := colour.RGBA()
if a == 0 {
return 1.0
}
max := maxColor(r, g, b)
min := minColor(r, g, b)
return (float64(max) + float64(min)) / (2 * 255)
}
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 drawCurves(img *image.NRGBA, opts *Options) {
for i := 0; i < opts.CurveNumber; i++ {
drawSineCurve(img, opts)
}
}
func drawSineCurve(img *image.NRGBA, opts *Options) {
var xStart, xEnd int
if opts.width <= 40 {
xStart, xEnd = 1, opts.width-1
} else {
xStart = rand.Intn(opts.width/10) + 1
xEnd = opts.width - rand.Intn(opts.width/10) - 1
}
curveHeight := float64(rand.Intn(opts.height/6) + opts.height/6)
yStart := rand.Intn(opts.height*2/3) + opts.height/6
angle := 1.0 + rand.Float64()
yFlip := 1.0
if rand.Intn(2) == 0 {
yFlip = -1.0
}
curveColor := randomColorFromOptions(opts)
for x1 := xStart; x1 <= xEnd; x1++ {
y := math.Sin(math.Pi*angle*float64(x1)/float64(opts.width)) * curveHeight * yFlip
img.Set(x1, int(y)+yStart, curveColor)
}
}
func drawText(text string, img *image.NRGBA, opts *Options) error {
ctx := freetype.NewContext()
ctx.SetDPI(opts.FontDPI)
ctx.SetClip(img.Bounds())
ctx.SetDst(img)
ctx.SetHinting(font.HintingFull)
ctx.SetFont(ttfFont)
fontSpacing := opts.width / len(text)
fontOffset := rand.Intn(fontSpacing / 2)
for idx, char := range text {
fontScale := 0.8 + rand.Float64()*0.4
fontSize := float64(opts.height) / fontScale * opts.FontScale
ctx.SetFontSize(fontSize)
ctx.SetSrc(image.NewUniform(randomColorFromOptions(opts)))
x := fontSpacing*idx + fontOffset
y := opts.height/6 + rand.Intn(opts.height/3) + int(fontSize/2)
pt := freetype.Pt(x, y)
if _, err := ctx.DrawString(string(char), pt); err != nil {
return err
}
}
return nil
}
func drawNoise(img *image.NRGBA, opts *Options) {
noiseCount := (opts.width * opts.height) / int(28.0/opts.Noise)
for i := 0; i < noiseCount; i++ {
x := rand.Intn(opts.width)
y := rand.Intn(opts.height)
img.Set(x, y, randomColor())
}
}