all repos — captcha @ c179a205da7d0e66a572f0798b189398bf492658

Go package captcha implements generation and verification of image and audio CAPTCHAs.

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	// Calculate sizes.
 44	img.calculateSizes(width, height, len(digits))
 45	// Draw background (10 random circles of random brightness).
 46	img.fillWithCircles(10, img.dotSize)
 47	// Randomly position captcha inside the image.
 48	maxx := width - (img.numWidth+img.dotSize)*len(digits) - img.dotSize
 49	maxy := height - img.numHeight - img.dotSize*2
 50	x := rnd(img.dotSize*2, maxx)
 51	y := rnd(img.dotSize*2, maxy)
 52	// Draw digits.
 53	for _, n := range digits {
 54		img.drawDigit(font[n], x, y)
 55		x += img.numWidth + img.dotSize
 56	}
 57	// Draw strike-through line.
 58	img.strikeThrough()
 59	return img
 60}
 61
 62// NewRandomImage generates a sequence of random digits with the given length,
 63// and returns a new captcha image of the given width and height with generated
 64// digits printed on it, and the sequence of digits itself.
 65func NewRandomImage(length, width, height int) (img *Image, digits []byte) {
 66	digits = randomDigits(length)
 67	img = NewImage(digits, width, height)
 68	return
 69}
 70
 71// WriteTo writes captcha image in PNG format into the given writer.
 72//
 73// Bug: while Image conforms to io.WriterTo interface, this function returns 0
 74// instead of the actual bytes written because png.Encode doesn't report this.
 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 / 5
 84	} else {
 85		border = width / 5
 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)
110	img.numHeight = int(nh) - img.dotSize
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	r := 0
159	maxx := img.Bounds().Max.X
160	maxy := img.Bounds().Max.Y
161	y := rnd(maxy/3, maxy-maxy/3)
162	for x := 0; x < maxx; x += r {
163		r = rnd(1, img.dotSize/2-1)
164		y += rnd(-img.dotSize/2, img.dotSize/2)
165		if y <= 0 || y >= maxy {
166			y = rnd(maxy/3, maxy-maxy/3)
167		}
168		img.drawCircle(img.primaryColor, x, y, r)
169	}
170}
171
172func (img *Image) drawDigit(digit []byte, x, y int) {
173	skf := rand.Float64() * float64(rnd(-maxSkew, maxSkew))
174	xs := float64(x)
175	minr := img.dotSize / 2               // minumum radius
176	maxr := img.dotSize/2 + img.dotSize/4 // maximum radius
177	y += rnd(-minr, minr)
178	for yy := 0; yy < fontHeight; yy++ {
179		for xx := 0; xx < fontWidth; xx++ {
180			if digit[yy*fontWidth+xx] != blackChar {
181				continue
182			}
183			// Introduce random variations.
184			or := rnd(minr, maxr)
185			ox := x + (xx * img.dotSize) + rnd(0, or/2)
186			oy := y + (yy * img.dotSize) + rnd(0, or/2)
187
188			img.drawCircle(img.primaryColor, ox, oy, or)
189		}
190		xs += skf
191		x = int(xs)
192	}
193}
194
195func setRandomBrightness(c *image.NRGBAColor, max uint8) {
196	minc := min3(c.R, c.G, c.B)
197	maxc := max3(c.R, c.G, c.B)
198	if maxc > max {
199		return
200	}
201	n := rand.Intn(int(max-maxc)) - int(minc)
202	c.R = uint8(int(c.R) + n)
203	c.G = uint8(int(c.G) + n)
204	c.B = uint8(int(c.B) + n)
205}
206
207func min3(x, y, z uint8) (o uint8) {
208	o = x
209	if y < o {
210		o = y
211	}
212	if z < o {
213		o = z
214	}
215	return
216}
217
218func max3(x, y, z uint8) (o uint8) {
219	o = x
220	if y > o {
221		o = y
222	}
223	if z > o {
224		o = z
225	}
226	return
227}
228
229// rnd returns a random number in range [from, to].
230func rnd(from, to int) int {
231	return rand.Intn(to+1-from) + from
232}