image.go (view raw)
1package captcha
2
3import (
4 "image"
5 "image/png"
6 "io"
7 "math"
8 "os"
9 "rand"
10 "time"
11)
12
13const (
14 // Standard width and height of a captcha image.
15 StdWidth = 240
16 StdHeight = 80
17 // Maximum absolute skew factor of a single digit.
18 maxSkew = 0.7
19 // Number of background circles.
20 circleCount = 20
21)
22
23type Image struct {
24 *image.Paletted
25 numWidth int
26 numHeight int
27 dotSize int
28}
29
30func init() {
31 rand.Seed(time.Seconds())
32}
33
34func randomPalette() image.PalettedColorModel {
35 p := make([]image.Color, circleCount+1)
36 // Transparent color.
37 // TODO(dchest). Currently it's white, not transparent, because PNG
38 // encoder doesn't support paletted images with alpha channel.
39 // Submitted CL: http://codereview.appspot.com/4432078 Change alpha to
40 // 0x00 once it's accepted.
41 p[0] = image.RGBAColor{0xFF, 0xFF, 0xFF, 0xFF}
42 // Primary color.
43 prim := image.RGBAColor{
44 uint8(rand.Intn(129)),
45 uint8(rand.Intn(129)),
46 uint8(rand.Intn(129)),
47 0xFF,
48 }
49 p[1] = prim
50 // Circle colors.
51 for i := 2; i <= circleCount; i++ {
52 p[i] = randomBrightness(prim, 255)
53 }
54 return p
55}
56
57// NewImage returns a new captcha image of the given width and height with the
58// given digits, where each digit must be in range 0-9.
59func NewImage(digits []byte, width, height int) *Image {
60 img := new(Image)
61 img.Paletted = image.NewPaletted(width, height, randomPalette())
62 img.calculateSizes(width, height, len(digits))
63 // Randomly position captcha inside the image.
64 maxx := width - (img.numWidth+img.dotSize)*len(digits) - img.dotSize
65 maxy := height - img.numHeight - img.dotSize*2
66 var border int
67 if width > height {
68 border = height / 5
69 } else {
70 border = width / 5
71 }
72 x := rnd(border, maxx-border)
73 y := rnd(border, maxy-border)
74 // Draw digits.
75 for _, n := range digits {
76 img.drawDigit(font[n], x, y)
77 x += img.numWidth + img.dotSize
78 }
79 // Draw strike-through line.
80 img.strikeThrough()
81 // Apply wave distortion.
82 img.distort(rndf(5, 10), rndf(100, 200))
83 // Fill image with random circles.
84 img.fillWithCircles(20, img.dotSize)
85 return img
86}
87
88// BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
89// method returns 0 instead of the actual bytes written because png.Encode
90// doesn't report this.
91
92// WriteTo writes captcha image in PNG format into the given writer.
93func (img *Image) WriteTo(w io.Writer) (int64, os.Error) {
94 return 0, png.Encode(w, img.Paletted)
95}
96
97func (img *Image) calculateSizes(width, height, ncount int) {
98 // Goal: fit all digits inside the image.
99 var border int
100 if width > height {
101 border = height / 4
102 } else {
103 border = width / 4
104 }
105 // Convert everything to floats for calculations.
106 w := float64(width - border*2)
107 h := float64(height - border*2)
108 // fw takes into account 1-dot spacing between digits.
109 fw := float64(fontWidth + 1)
110 fh := float64(fontHeight)
111 nc := float64(ncount)
112 // Calculate the width of a single digit taking into account only the
113 // width of the image.
114 nw := w / nc
115 // Calculate the height of a digit from this width.
116 nh := nw * fh / fw
117 // Digit too high?
118 if nh > h {
119 // Fit digits based on height.
120 nh = h
121 nw = fw / fh * nh
122 }
123 // Calculate dot size.
124 img.dotSize = int(nh / fh)
125 // Save everything, making the actual width smaller by 1 dot to account
126 // for spacing between digits.
127 img.numWidth = int(nw) - img.dotSize
128 img.numHeight = int(nh)
129}
130
131func (img *Image) drawHorizLine(fromX, toX, y int, colorIndex uint8) {
132 for x := fromX; x <= toX; x++ {
133 img.SetColorIndex(x, y, colorIndex)
134 }
135}
136
137func (img *Image) drawCircle(x, y, radius int, colorIndex uint8) {
138 f := 1 - radius
139 dfx := 1
140 dfy := -2 * radius
141 xx := 0
142 yy := radius
143
144 img.SetColorIndex(x, y+radius, colorIndex)
145 img.SetColorIndex(x, y-radius, colorIndex)
146 img.drawHorizLine(x-radius, x+radius, y, colorIndex)
147
148 for xx < yy {
149 if f >= 0 {
150 yy--
151 dfy += 2
152 f += dfy
153 }
154 xx++
155 dfx += 2
156 f += dfx
157 img.drawHorizLine(x-xx, x+xx, y+yy, colorIndex)
158 img.drawHorizLine(x-xx, x+xx, y-yy, colorIndex)
159 img.drawHorizLine(x-yy, x+yy, y+xx, colorIndex)
160 img.drawHorizLine(x-yy, x+yy, y-xx, colorIndex)
161 }
162}
163
164func (img *Image) fillWithCircles(n, maxradius int) {
165 maxx := img.Bounds().Max.X
166 maxy := img.Bounds().Max.Y
167 for i := 0; i < n; i++ {
168 colorIndex := uint8(rnd(1, circleCount-1))
169 r := rnd(1, maxradius)
170 img.drawCircle(rnd(r, maxx-r), rnd(r, maxy-r), r, colorIndex)
171 }
172}
173
174func (img *Image) strikeThrough() {
175 maxx := img.Bounds().Max.X
176 maxy := img.Bounds().Max.Y
177 y := rnd(maxy/3, maxy-maxy/3)
178 amplitude := rndf(5, 20)
179 period := rndf(80, 180)
180 dx := 2.0 * math.Pi / period
181 for x := 0; x < maxx; x++ {
182 xo := amplitude * math.Cos(float64(y)*dx)
183 yo := amplitude * math.Sin(float64(x)*dx)
184 for yn := 0; yn < img.dotSize; yn++ {
185 r := rnd(0, img.dotSize)
186 img.drawCircle(x+int(xo), y+int(yo)+(yn*img.dotSize), r/2, 1)
187 }
188 }
189}
190
191func (img *Image) drawDigit(digit []byte, x, y int) {
192 skf := rndf(-maxSkew, maxSkew)
193 xs := float64(x)
194 r := img.dotSize / 2
195 y += rnd(-r, r)
196 for yy := 0; yy < fontHeight; yy++ {
197 for xx := 0; xx < fontWidth; xx++ {
198 if digit[yy*fontWidth+xx] != blackChar {
199 continue
200 }
201 ox := x + xx*img.dotSize
202 oy := y + yy*img.dotSize
203 img.drawCircle(ox, oy, r, 1)
204 }
205 xs += skf
206 x = int(xs)
207 }
208}
209
210func (img *Image) distort(amplude float64, period float64) {
211 w := img.Bounds().Max.X
212 h := img.Bounds().Max.Y
213
214 oldImg := img.Paletted
215 newImg := image.NewPaletted(w, h, oldImg.Palette)
216
217 dx := 2.0 * math.Pi / period
218 for x := 0; x < w; x++ {
219 for y := 0; y < h; y++ {
220 ox := amplude * math.Sin(float64(y)*dx)
221 oy := amplude * math.Cos(float64(x)*dx)
222 newImg.SetColorIndex(x, y, oldImg.ColorIndexAt(x+int(ox), y+int(oy)))
223 }
224 }
225 img.Paletted = newImg
226}
227
228func randomBrightness(c image.RGBAColor, max uint8) image.RGBAColor {
229 minc := min3(c.R, c.G, c.B)
230 maxc := max3(c.R, c.G, c.B)
231 if maxc > max {
232 return c
233 }
234 n := rand.Intn(int(max-maxc)) - int(minc)
235 return image.RGBAColor{
236 uint8(int(c.R) + n),
237 uint8(int(c.G) + n),
238 uint8(int(c.B) + n),
239 uint8(c.A),
240 }
241}
242
243func min3(x, y, z uint8) (o uint8) {
244 o = x
245 if y < o {
246 o = y
247 }
248 if z < o {
249 o = z
250 }
251 return
252}
253
254func max3(x, y, z uint8) (o uint8) {
255 o = x
256 if y > o {
257 o = y
258 }
259 if z > o {
260 o = z
261 }
262 return
263}
264
265// rnd returns a random number in range [from, to].
266func rnd(from, to int) int {
267 return rand.Intn(to+1-from) + from
268}