all repos — captcha @ e3eb22480f6e652f321e379501124c5c62318fc2

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