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