all repos — captcha @ 452b826a09ebcd13b9b782d48f55882f951f0f31

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 for captcha image
 14	StdWidth  = 300
 15	StdHeight = 80
 16
 17	maxSkew = 2
 18)
 19
 20type CaptchaImage 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 slice of numbers, where each number must be in range 0-9.
 34func NewImage(numbers []byte, width, height int) *CaptchaImage {
 35	img := new(CaptchaImage)
 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	var border int
 45	if width > height {
 46		border = height / 5
 47	} else {
 48		border = width / 5
 49	}
 50	bwidth := width - border*2
 51	bheight := height - border*2
 52	img.calculateSizes(bwidth, bheight, len(numbers))
 53	// Draw background (10 random circles of random brightness)
 54	img.fillWithCircles(10, img.dotSize)
 55	// Randomly position captcha inside the image
 56	maxx := width - (img.numWidth+img.dotSize)*len(numbers) - img.dotSize
 57	maxy := height - img.numHeight - img.dotSize*2
 58	x := rnd(img.dotSize*2, maxx)
 59	y := rnd(img.dotSize*2, maxy)
 60	// Draw numbers
 61	for _, n := range numbers {
 62		img.drawNumber(font[n], x, y)
 63		x += img.numWidth + img.dotSize
 64	}
 65	// Draw strike-through line
 66	img.strikeThrough()
 67	return img
 68}
 69
 70// NewRandomImage generates a sequence of random numbers with the given length,
 71// and returns a new captcha image of the given width and height with generated
 72// numbers printed on it, and the sequence of numbers itself.
 73func NewRandomImage(length, width, height int) (img *CaptchaImage, numbers []byte) {
 74	numbers = randomNumbers(length)
 75	img = NewImage(numbers, width, height)
 76	return
 77}
 78
 79// PNGEncode writes captcha image in PNG format into the given writer.
 80func (img *CaptchaImage) PNGEncode(w io.Writer) os.Error {
 81	return png.Encode(w, img)
 82}
 83
 84func (img *CaptchaImage) calculateSizes(width, height, ncount int) {
 85	// Goal: fit all numbers inside the image.
 86	// Convert everything to floats for calculations
 87	w := float64(width)
 88	h := float64(height)
 89	// fw takes into account 1-dot spacing between numbers
 90	fw := float64(fontWidth) + 1
 91	fh := float64(fontHeight)
 92	nc := float64(ncount)
 93	// Calculate the width of a single number taking into account only the
 94	// width of the image
 95	nw := w / nc
 96	// Calculate the height of a number from this width
 97	nh := nw * fh / fw
 98	// Number height too large?
 99	if nh > h {
100		// Fit numbers based on height
101		nh = h
102		nw = fw / fh * nh
103	}
104	// Calculate dot size
105	img.dotSize = int(nh / fh)
106	// Save everything, making the actual width smaller by 1 dot to account
107	// for spacing between numbers
108	img.numWidth = int(nw)
109	img.numHeight = int(nh) - img.dotSize
110}
111
112func (img *CaptchaImage) drawHorizLine(color image.Color, fromX, toX, y int) {
113	for x := fromX; x <= toX; x++ {
114		img.Set(x, y, color)
115	}
116}
117
118func (img *CaptchaImage) drawCircle(color image.Color, x, y, radius int) {
119	f := 1 - radius
120	dfx := 1
121	dfy := -2 * radius
122	xx := 0
123	yy := radius
124
125	img.Set(x, y+radius, color)
126	img.Set(x, y-radius, color)
127	img.drawHorizLine(color, x-radius, x+radius, y)
128
129	for xx < yy {
130		if f >= 0 {
131			yy--
132			dfy += 2
133			f += dfy
134		}
135		xx++
136		dfx += 2
137		f += dfx
138		img.drawHorizLine(color, x-xx, x+xx, y+yy)
139		img.drawHorizLine(color, x-xx, x+xx, y-yy)
140		img.drawHorizLine(color, x-yy, x+yy, y+xx)
141		img.drawHorizLine(color, x-yy, x+yy, y-xx)
142	}
143}
144
145func (img *CaptchaImage) fillWithCircles(n, maxradius int) {
146	color := img.primaryColor
147	maxx := img.Bounds().Max.X
148	maxy := img.Bounds().Max.Y
149	for i := 0; i < n; i++ {
150		setRandomBrightness(&color, 255)
151		r := rnd(1, maxradius)
152		img.drawCircle(color, rnd(r, maxx-r), rnd(r, maxy-r), r)
153	}
154}
155
156func (img *CaptchaImage) strikeThrough() {
157	r := 0
158	maxx := img.Bounds().Max.X
159	maxy := img.Bounds().Max.Y
160	y := rnd(maxy/3, maxy-maxy/3)
161	for x := 0; x < maxx; x += r {
162		r = rnd(1, img.dotSize/2-1)
163		y += rnd(-img.dotSize/2, img.dotSize/2)
164		if y <= 0 || y >= maxy {
165			y = rnd(maxy/3, maxy-maxy/3)
166		}
167		img.drawCircle(img.primaryColor, x, y, r)
168	}
169}
170
171func (img *CaptchaImage) drawNumber(number []byte, x, y int) {
172	skf := rand.Float64() * float64(rnd(-maxSkew, maxSkew))
173	xs := float64(x)
174	minr := img.dotSize / 2               // minumum radius
175	maxr := img.dotSize/2 + img.dotSize/4 // maximum radius
176	y += rnd(-minr, minr)
177	for yy := 0; yy < fontHeight; yy++ {
178		for xx := 0; xx < fontWidth; xx++ {
179			if number[yy*fontWidth+xx] != blackChar {
180				continue
181			}
182			// introduce random variations
183			or := rnd(minr, maxr)
184			ox := x + (xx * img.dotSize) + rnd(0, or/2)
185			oy := y + (yy * img.dotSize) + rnd(0, or/2)
186			img.drawCircle(img.primaryColor, ox, oy, or)
187		}
188		xs += skf
189		x = int(xs)
190	}
191}
192
193func setRandomBrightness(c *image.NRGBAColor, max uint8) {
194	minc := min3(c.R, c.G, c.B)
195	maxc := max3(c.R, c.G, c.B)
196	if maxc > max {
197		return
198	}
199	n := rand.Intn(int(max-maxc)) - int(minc)
200	c.R = uint8(int(c.R) + n)
201	c.G = uint8(int(c.G) + n)
202	c.B = uint8(int(c.B) + n)
203}
204
205func min3(x, y, z uint8) (o uint8) {
206	o = x
207	if y < o {
208		o = y
209	}
210	if z < o {
211		o = z
212	}
213	return
214}
215
216func max3(x, y, z uint8) (o uint8) {
217	o = x
218	if y > o {
219		o = y
220	}
221	if z > o {
222		o = z
223	}
224	return
225}
226
227// rnd returns a random number in range [from, to].
228func rnd(from, to int) int {
229	return rand.Intn(to+1-from) + from
230}