all repos — captcha @ f14d4a9979825b6bc693f15cc3fc97b26145562b

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	"math"
  8	"os"
  9	"rand"
 10)
 11
 12const (
 13	// Standard width and height of a captcha image.
 14	StdWidth  = 240
 15	StdHeight = 80
 16	// Maximum absolute skew factor of a single digit.
 17	maxSkew = 0.7
 18	// Number of background circles.
 19	circleCount = 20
 20)
 21
 22type Image struct {
 23	*image.Paletted
 24	numWidth  int
 25	numHeight int
 26	dotSize   int
 27}
 28
 29func randomPalette() image.PalettedColorModel {
 30	p := make([]image.Color, circleCount+1)
 31	// Transparent color.
 32	// TODO(dchest). Currently it's white, not transparent, because PNG
 33	// encoder doesn't support paletted images with alpha channel.
 34	// Submitted CL: http://codereview.appspot.com/4432078 Change alpha to
 35	// 0x00 once it's accepted.
 36	p[0] = image.RGBAColor{0xFF, 0xFF, 0xFF, 0xFF}
 37	// Primary color.
 38	prim := image.RGBAColor{
 39		uint8(rand.Intn(129)),
 40		uint8(rand.Intn(129)),
 41		uint8(rand.Intn(129)),
 42		0xFF,
 43	}
 44	p[1] = prim
 45	// Circle colors.
 46	for i := 2; i <= circleCount; i++ {
 47		p[i] = randomBrightness(prim, 255)
 48	}
 49	return p
 50}
 51
 52// NewImage returns a new captcha image of the given width and height with the
 53// given digits, where each digit must be in range 0-9.
 54func NewImage(digits []byte, width, height int) *Image {
 55	img := new(Image)
 56	img.Paletted = image.NewPaletted(width, height, randomPalette())
 57	img.calculateSizes(width, height, len(digits))
 58	// Randomly position captcha inside the image.
 59	maxx := width - (img.numWidth+img.dotSize)*len(digits) - img.dotSize
 60	maxy := height - img.numHeight - img.dotSize*2
 61	var border int
 62	if width > height {
 63		border = height / 5
 64	} else {
 65		border = width / 5
 66	}
 67	x := rnd(border, maxx-border)
 68	y := rnd(border, maxy-border)
 69	// Draw digits.
 70	for _, n := range digits {
 71		img.drawDigit(font[n], x, y)
 72		x += img.numWidth + img.dotSize
 73	}
 74	// Draw strike-through line.
 75	img.strikeThrough()
 76	// Apply wave distortion.
 77	img.distort(rndf(5, 10), rndf(100, 200))
 78	// Fill image with random circles.
 79	img.fillWithCircles(circleCount, img.dotSize)
 80	return img
 81}
 82
 83// BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
 84// method returns 0 instead of the actual bytes written because png.Encode
 85// doesn't report this.
 86
 87// WriteTo writes captcha image in PNG format into the given writer.
 88func (img *Image) WriteTo(w io.Writer) (int64, os.Error) {
 89	return 0, png.Encode(w, img.Paletted)
 90}
 91
 92func (img *Image) calculateSizes(width, height, ncount int) {
 93	// Goal: fit all digits inside the image.
 94	var border int
 95	if width > height {
 96		border = height / 4
 97	} else {
 98		border = width / 4
 99	}
100	// Convert everything to floats for calculations.
101	w := float64(width - border*2)
102	h := float64(height - border*2)
103	// fw takes into account 1-dot spacing between digits.
104	fw := float64(fontWidth + 1)
105	fh := float64(fontHeight)
106	nc := float64(ncount)
107	// Calculate the width of a single digit taking into account only the
108	// width of the image.
109	nw := w / nc
110	// Calculate the height of a digit from this width.
111	nh := nw * fh / fw
112	// Digit too high?
113	if nh > h {
114		// Fit digits based on height.
115		nh = h
116		nw = fw / fh * nh
117	}
118	// Calculate dot size.
119	img.dotSize = int(nh / fh)
120	// Save everything, making the actual width smaller by 1 dot to account
121	// for spacing between digits.
122	img.numWidth = int(nw) - img.dotSize
123	img.numHeight = int(nh)
124}
125
126func (img *Image) drawHorizLine(fromX, toX, y int, colorIndex uint8) {
127	for x := fromX; x <= toX; x++ {
128		img.SetColorIndex(x, y, colorIndex)
129	}
130}
131
132func (img *Image) drawCircle(x, y, radius int, colorIndex uint8) {
133	f := 1 - radius
134	dfx := 1
135	dfy := -2 * radius
136	xx := 0
137	yy := radius
138
139	img.SetColorIndex(x, y+radius, colorIndex)
140	img.SetColorIndex(x, y-radius, colorIndex)
141	img.drawHorizLine(x-radius, x+radius, y, colorIndex)
142
143	for xx < yy {
144		if f >= 0 {
145			yy--
146			dfy += 2
147			f += dfy
148		}
149		xx++
150		dfx += 2
151		f += dfx
152		img.drawHorizLine(x-xx, x+xx, y+yy, colorIndex)
153		img.drawHorizLine(x-xx, x+xx, y-yy, colorIndex)
154		img.drawHorizLine(x-yy, x+yy, y+xx, colorIndex)
155		img.drawHorizLine(x-yy, x+yy, y-xx, colorIndex)
156	}
157}
158
159func (img *Image) fillWithCircles(n, maxradius int) {
160	maxx := img.Bounds().Max.X
161	maxy := img.Bounds().Max.Y
162	for i := 0; i < n; i++ {
163		colorIndex := uint8(rnd(1, circleCount-1))
164		r := rnd(1, maxradius)
165		img.drawCircle(rnd(r, maxx-r), rnd(r, maxy-r), r, colorIndex)
166	}
167}
168
169func (img *Image) strikeThrough() {
170	maxx := img.Bounds().Max.X
171	maxy := img.Bounds().Max.Y
172	y := rnd(maxy/3, maxy-maxy/3)
173	amplitude := rndf(5, 20)
174	period := rndf(80, 180)
175	dx := 2.0 * math.Pi / period
176	for x := 0; x < maxx; x++ {
177		xo := amplitude * math.Cos(float64(y)*dx)
178		yo := amplitude * math.Sin(float64(x)*dx)
179		for yn := 0; yn < img.dotSize; yn++ {
180			r := rnd(0, img.dotSize)
181			img.drawCircle(x+int(xo), y+int(yo)+(yn*img.dotSize), r/2, 1)
182		}
183	}
184}
185
186func (img *Image) drawDigit(digit []byte, x, y int) {
187	skf := rndf(-maxSkew, maxSkew)
188	xs := float64(x)
189	r := img.dotSize / 2
190	y += rnd(-r, r)
191	for yy := 0; yy < fontHeight; yy++ {
192		for xx := 0; xx < fontWidth; xx++ {
193			if digit[yy*fontWidth+xx] != blackChar {
194				continue
195			}
196			ox := x + xx*img.dotSize
197			oy := y + yy*img.dotSize
198			img.drawCircle(ox, oy, r, 1)
199		}
200		xs += skf
201		x = int(xs)
202	}
203}
204
205func (img *Image) distort(amplude float64, period float64) {
206	w := img.Bounds().Max.X
207	h := img.Bounds().Max.Y
208
209	oldImg := img.Paletted
210	newImg := image.NewPaletted(w, h, oldImg.Palette)
211
212	dx := 2.0 * math.Pi / period
213	for x := 0; x < w; x++ {
214		for y := 0; y < h; y++ {
215			ox := amplude * math.Sin(float64(y)*dx)
216			oy := amplude * math.Cos(float64(x)*dx)
217			newImg.SetColorIndex(x, y, oldImg.ColorIndexAt(x+int(ox), y+int(oy)))
218		}
219	}
220	img.Paletted = newImg
221}
222
223func randomBrightness(c image.RGBAColor, max uint8) image.RGBAColor {
224	minc := min3(c.R, c.G, c.B)
225	maxc := max3(c.R, c.G, c.B)
226	if maxc > max {
227		return c
228	}
229	n := rand.Intn(int(max-maxc)) - int(minc)
230	return image.RGBAColor{
231		uint8(int(c.R) + n),
232		uint8(int(c.G) + n),
233		uint8(int(c.B) + n),
234		uint8(c.A),
235	}
236}
237
238func min3(x, y, z uint8) (o uint8) {
239	o = x
240	if y < o {
241		o = y
242	}
243	if z < o {
244		o = z
245	}
246	return
247}
248
249func max3(x, y, z uint8) (o uint8) {
250	o = x
251	if y > o {
252		o = y
253	}
254	if z > o {
255		o = z
256	}
257	return
258}