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