Debian Codegraph @

image.go

raw symbols SCIP
1 // Copyright 2011-2014 Dmitry Chestnykh. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package captcha
6
7 import (
8 "bytes"
9 "image"
10 "image/color"
11 "image/png"
12 "io"
13 "math"
14 mathRand "math/rand/v2"
15 )
16
17 const (
18 // Standard width and height of a captcha image.
19 StdWidth = 240
20 StdHeight = 80
21 // Maximum absolute skew factor of a single digit.
22 maxSkew = 0.7
23 // Number of background circles.
24 circleCount = 20
25 )
26
27 type Image struct {
28 *image.Paletted
29 numWidth int
30 numHeight int
31 dotSize int
32 rng *mathRand.Rand
33 }
34
35 // Int returns a pseudorandom int in the half-open interval [from, to].
36 func (m *Image) Int(from, to int) int {
37 return from + m.rng.IntN(to-from+1)
38 }
39
40 // Float returns a pseudorandom float64 in the half-open interval [from, to).
41 func (m *Image) Float(from, to float64) float64 {
42 return from + (to-from)*m.rng.Float64()
43 }
44
45 // NewImage returns a new captcha image of the given width and height with the
46 // given digits, where each digit must be in range 0-9.
47 func NewImage(id string, digits []byte, width, height int) *Image {
48 m := new(Image)
49
50 // Initialize PRNG.
51 m.rng = mathRand.New(mathRand.NewChaCha8(deriveSeed(imageSeedPurpose, id, digits)))
52
53 m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), m.getRandomPalette())
54 m.calculateSizes(width, height, len(digits))
55 // Randomly position captcha inside the image.
56 maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize
57 maxy := height - m.numHeight - m.dotSize*2
58 var border int
59 if width > height {
60 border = height / 5
61 } else {
62 border = width / 5
63 }
64 x := m.Int(border, maxx-border)
65 y := m.Int(border, maxy-border)
66 // Draw digits.
67 for _, n := range digits {
68 m.drawDigit(font[n], x, y)
69 x += m.numWidth + m.dotSize
70 }
71 // Draw strike-through line.
72 m.strikeThrough()
73 // Apply wave distortion.
74 m.distort(m.Float(5, 10), m.Float(100, 200))
75 // Fill image with random circles.
76 m.fillWithCircles(circleCount, m.dotSize)
77 // Flip the image horizontally.
78 m.flipX()
79 return m
80 }
81
82 func (m *Image) getRandomPalette() color.Palette {
83 p := make([]color.Color, circleCount+1)
84 // Transparent color.
85 p[0] = color.RGBA{0xFF, 0xFF, 0xFF, 0x00}
86 // Primary color.
87 prim := color.RGBA{
88 uint8(m.rng.IntN(129)),
89 uint8(m.rng.IntN(129)),
90 uint8(m.rng.IntN(129)),
91 0xFF,
92 }
93 p[1] = prim
94 // Circle colors.
95 for i := 2; i <= circleCount; i++ {
96 p[i] = m.randomBrightness(prim, 255)
97 }
98 return p
99 }
100
101 // encodedPNG encodes an image to PNG and returns
102 // the result as a byte slice.
103 func (m *Image) encodedPNG() []byte {
104 var buf bytes.Buffer
105 if err := png.Encode(&buf, m.Paletted); err != nil {
106 panic(err.Error())
107 }
108 return buf.Bytes()
109 }
110
111 // WriteTo writes captcha image in PNG format into the given writer.
112 func (m *Image) WriteTo(w io.Writer) (int64, error) {
113 n, err := w.Write(m.encodedPNG())
114 return int64(n), err
115 }
116
117 func (m *Image) calculateSizes(width, height, ncount int) {
118 // Goal: fit all digits inside the image.
119 var border int
120 if width > height {
121 border = height / 4
122 } else {
123 border = width / 4
124 }
125 // Convert everything to floats for calculations.
126 w := float64(width - border*2)
127 h := float64(height - border*2)
128 // fw takes into account 1-dot spacing between digits.
129 fw := float64(fontWidth + 1)
130 fh := float64(fontHeight)
131 nc := float64(ncount)
132 // Calculate the width of a single digit taking into account only the
133 // width of the image.
134 nw := w / nc
135 // Calculate the height of a digit from this width.
136 nh := nw * fh / fw
137 // Digit too high?
138 if nh > h {
139 // Fit digits based on height.
140 nh = h
141 nw = fw / fh * nh
142 }
143 // Calculate dot size.
144 m.dotSize = max(int(nh/fh), 1)
145 // Save everything, making the actual width smaller by 1 dot to account
146 // for spacing between digits.
147 m.numWidth = int(nw) - m.dotSize
148 m.numHeight = int(nh)
149 }
150
151 func (m *Image) drawHorizLine(fromX, toX, y int, colorIdx uint8) {
152 for x := fromX; x <= toX; x++ {
153 m.SetColorIndex(x, y, colorIdx)
154 }
155 }
156
157 func (m *Image) drawCircle(x, y, radius int, colorIdx uint8) {
158 f := 1 - radius
159 dfx := 1
160 dfy := -2 * radius
161 xo := 0
162 yo := radius
163
164 m.SetColorIndex(x, y+radius, colorIdx)
165 m.SetColorIndex(x, y-radius, colorIdx)
166 m.drawHorizLine(x-radius, x+radius, y, colorIdx)
167
168 for xo < yo {
169 if f >= 0 {
170 yo--
171 dfy += 2
172 f += dfy
173 }
174 xo++
175 dfx += 2
176 f += dfx
177 m.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
178 m.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
179 m.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
180 m.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
181 }
182 }
183
184 func (m *Image) fillWithCircles(n, maxradius int) {
185 maxx := m.Bounds().Max.X
186 maxy := m.Bounds().Max.Y
187 for range n {
188 colorIdx := uint8(m.Int(1, circleCount-1))
189 r := m.Int(1, maxradius)
190 m.drawCircle(m.Int(r, maxx-r), m.Int(r, maxy-r), r, colorIdx)
191 }
192 }
193
194 func (m *Image) strikeThrough() {
195 maxx := m.Bounds().Max.X
196 maxy := m.Bounds().Max.Y
197 y := m.Int(maxy/3, maxy-maxy/3)
198 amplitude := m.Float(5, 20)
199 period := m.Float(80, 180)
200 dx := 2.0 * math.Pi / period
201 for x := range maxx {
202 xo := amplitude * math.Cos(float64(y)*dx)
203 yo := amplitude * math.Sin(float64(x)*dx)
204 for yn := 0; yn < m.dotSize; yn++ {
205 r := m.rng.IntN(m.dotSize + 1)
206 m.drawCircle(x+int(xo), y+int(yo)+(yn*m.dotSize), r/2, 1)
207 }
208 }
209 }
210
211 func (m *Image) drawDigit(digit []byte, x, y int) {
212 skf := m.Float(-maxSkew, maxSkew)
213 xs := float64(x)
214 r := m.dotSize / 2
215 y += m.Int(-r, r)
216 for yo := range fontHeight {
217 for xo := range fontWidth {
218 if digit[yo*fontWidth+xo] != blackChar {
219 continue
220 }
221 m.drawCircle(x+xo*m.dotSize, y+yo*m.dotSize, r, 1)
222 }
223 xs += skf
224 x = int(xs)
225 }
226 }
227
228 func (m *Image) distort(amplude float64, period float64) {
229 w := m.Bounds().Max.X
230 h := m.Bounds().Max.Y
231
232 oldm := m.Paletted
233 newm := image.NewPaletted(image.Rect(0, 0, w, h), oldm.Palette)
234
235 dx := 2.0 * math.Pi / period
236 for x := range w {
237 for y := range h {
238 xo := amplude * math.Sin(float64(y)*dx)
239 yo := amplude * math.Cos(float64(x)*dx)
240 newm.SetColorIndex(x, y, oldm.ColorIndexAt(x+int(xo), y+int(yo)))
241 }
242 }
243 m.Paletted = newm
244 }
245
246 func (m *Image) flipX() {
247 w := m.Bounds().Max.X
248 h := m.Bounds().Max.Y
249
250 src := m.Paletted
251 dst := image.NewPaletted(image.Rect(0, 0, w, h), src.Palette)
252
253 for x := range w {
254 for y := range h {
255 xo := w - x - 1
256 dst.SetColorIndex(x, y, src.ColorIndexAt(xo, y))
257 }
258 }
259 m.Paletted = dst
260 }
261
262 func (m *Image) randomBrightness(c color.RGBA, maxB uint8) color.RGBA {
263 minc := min(min(c.R, c.G), c.B)
264 maxc := max(max(c.R, c.G), c.B)
265 if maxc > maxB {
266 return c
267 }
268 n := m.rng.IntN(int(maxB-maxc)) - int(minc)
269 return color.RGBA{
270 uint8(int(c.R) + n),
271 uint8(int(c.G) + n),
272 uint8(int(c.B) + n),
273 c.A,
274 }
275 }