all repos — captcha @ e40250a1247fc6f98cb9d209ffe875af18f7d68c

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 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 slice of numbers, where each number must be in range 0-9.
 34func NewImage(numbers []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(numbers))
 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(numbers) - 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 numbers
 53	for _, n := range numbers {
 54		img.drawNumber(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 numbers with the given length,
 63// and returns a new captcha image of the given width and height with generated
 64// numbers printed on it, and the sequence of numbers itself.
 65func NewRandomImage(length, width, height int) (img *Image, numbers []byte) {
 66	numbers = randomNumbers(length)
 67	img = NewImage(numbers, 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 numbers 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 numbers
 91	fw := float64(fontWidth) + 1
 92	fh := float64(fontHeight)
 93	nc := float64(ncount)
 94	// Calculate the width of a single number taking into account only the
 95	// width of the image
 96	nw := w / nc
 97	// Calculate the height of a number from this width
 98	nh := nw * fh / fw
 99	// Number height too large?
100	if nh > h {
101		// Fit numbers 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 numbers
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) drawNumber(number []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 number[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			img.drawCircle(img.primaryColor, ox, oy, or)
188		}
189		xs += skf
190		x = int(xs)
191	}
192}
193
194func setRandomBrightness(c *image.NRGBAColor, max uint8) {
195	minc := min3(c.R, c.G, c.B)
196	maxc := max3(c.R, c.G, c.B)
197	if maxc > max {
198		return
199	}
200	n := rand.Intn(int(max-maxc)) - int(minc)
201	c.R = uint8(int(c.R) + n)
202	c.G = uint8(int(c.G) + n)
203	c.B = uint8(int(c.B) + n)
204}
205
206func min3(x, y, z uint8) (o uint8) {
207	o = x
208	if y < o {
209		o = y
210	}
211	if z < o {
212		o = z
213	}
214	return
215}
216
217func max3(x, y, z uint8) (o uint8) {
218	o = x
219	if y > o {
220		o = y
221	}
222	if z > o {
223		o = z
224	}
225	return
226}
227
228// rnd returns a random number in range [from, to].
229func rnd(from, to int) int {
230	return rand.Intn(to+1-from) + from
231}