all repos — captcha @ e6fb73402841aa4835165d9402634587e948de8e

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, colorIdx uint8) {
127	for x := fromX; x <= toX; x++ {
128		img.SetColorIndex(x, y, colorIdx)
129	}
130}
131
132func (img *Image) drawCircle(x, y, radius int, colorIdx uint8) {
133	f := 1 - radius
134	dfx := 1
135	dfy := -2 * radius
136	xo := 0
137	yo := radius
138
139	img.SetColorIndex(x, y+radius, colorIdx)
140	img.SetColorIndex(x, y-radius, colorIdx)
141	img.drawHorizLine(x-radius, x+radius, y, colorIdx)
142
143	for xo < yo {
144		if f >= 0 {
145			yo--
146			dfy += 2
147			f += dfy
148		}
149		xo++
150		dfx += 2
151		f += dfx
152		img.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
153		img.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
154		img.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
155		img.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
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		colorIdx := uint8(rnd(1, circleCount-1))
164		r := rnd(1, maxradius)
165		img.drawCircle(rnd(r, maxx-r), rnd(r, maxy-r), r, colorIdx)
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 yo := 0; yo < fontHeight; yo++ {
192		for xo := 0; xo < fontWidth; xo++ {
193			if digit[yo*fontWidth+xo] != blackChar {
194				continue
195			}
196			img.drawCircle(x+xo*img.dotSize, y+yo*img.dotSize, r, 1)
197		}
198		xs += skf
199		x = int(xs)
200	}
201}
202
203func (img *Image) distort(amplude float64, period float64) {
204	w := img.Bounds().Max.X
205	h := img.Bounds().Max.Y
206
207	oldImg := img.Paletted
208	newImg := image.NewPaletted(w, h, oldImg.Palette)
209
210	dx := 2.0 * math.Pi / period
211	for x := 0; x < w; x++ {
212		for y := 0; y < h; y++ {
213			xo := amplude * math.Sin(float64(y)*dx)
214			yo := amplude * math.Cos(float64(x)*dx)
215			newImg.SetColorIndex(x, y, oldImg.ColorIndexAt(x+int(xo), y+int(yo)))
216		}
217	}
218	img.Paletted = newImg
219}
220
221func randomBrightness(c image.RGBAColor, max uint8) image.RGBAColor {
222	minc := min3(c.R, c.G, c.B)
223	maxc := max3(c.R, c.G, c.B)
224	if maxc > max {
225		return c
226	}
227	n := rand.Intn(int(max-maxc)) - int(minc)
228	return image.RGBAColor{
229		uint8(int(c.R) + n),
230		uint8(int(c.G) + n),
231		uint8(int(c.B) + n),
232		uint8(c.A),
233	}
234}
235
236func min3(x, y, z uint8) (m uint8) {
237	m = x
238	if y < m {
239		m = y
240	}
241	if z < m {
242		m = z
243	}
244	return
245}
246
247func max3(x, y, z uint8) (m uint8) {
248	m = x
249	if y > m {
250		m = y
251	}
252	if z > m {
253		m = z
254	}
255	return
256}