all repos — captcha @ fe75d4b6ccdec05c8e3cd271f1815240625c7c2a

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	"time"
 11)
 12
 13const (
 14	// Standard width and height of a captcha image.
 15	StdWidth  = 240
 16	StdHeight = 80
 17	// Maximum absolute skew factor of a single digit.
 18	maxSkew = 0.7
 19)
 20
 21type Image struct {
 22	*image.NRGBA
 23	primaryColor image.NRGBAColor
 24	numWidth     int
 25	numHeight    int
 26	dotSize      int
 27}
 28
 29func init() {
 30	rand.Seed(time.Seconds())
 31}
 32
 33// NewImage returns a new captcha image of the given width and height with the
 34// given digits, where each digit must be in range 0-9.
 35func NewImage(digits []byte, width, height int) *Image {
 36	img := new(Image)
 37	img.NRGBA = image.NewNRGBA(width, height)
 38	img.primaryColor = image.NRGBAColor{
 39		uint8(rand.Intn(129)),
 40		uint8(rand.Intn(129)),
 41		uint8(rand.Intn(129)),
 42		0xFF,
 43	}
 44	img.calculateSizes(width, height, len(digits))
 45	// Randomly position captcha inside the image.
 46	maxx := width - (img.numWidth+img.dotSize)*len(digits) - img.dotSize
 47	maxy := height - img.numHeight - img.dotSize*2
 48	var border int
 49	if width > height {
 50		border = height / 5
 51	} else {
 52		border = width / 5
 53	}
 54	x := rnd(border, maxx-border)
 55	y := rnd(border, maxy-border)
 56	// Draw digits.
 57	for _, n := range digits {
 58		img.drawDigit(font[n], x, y)
 59		x += img.numWidth + img.dotSize
 60	}
 61	// Draw strike-through line.
 62	img.strikeThrough()
 63	// Apply wave distortion.
 64	img.distort(rndf(5, 10), rndf(100, 200))
 65	// Fill image with random circles.
 66	img.fillWithCircles(20, img.dotSize)
 67	return img
 68}
 69
 70// BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
 71// method returns 0 instead of the actual bytes written because png.Encode
 72// doesn't report this.
 73
 74// WriteTo writes captcha image in PNG format into the given writer.
 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 digits inside the image.
 81	var border int
 82	if width > height {
 83		border = height / 4
 84	} else {
 85		border = width / 4
 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 digits.
 91	fw := float64(fontWidth + 1)
 92	fh := float64(fontHeight)
 93	nc := float64(ncount)
 94	// Calculate the width of a single digit taking into account only the
 95	// width of the image.
 96	nw := w / nc
 97	// Calculate the height of a digit from this width.
 98	nh := nw * fh / fw
 99	// Digit too high?
100	if nh > h {
101		// Fit digits 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 digits.
109	img.numWidth = int(nw) - img.dotSize
110	img.numHeight = int(nh)
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	maxx := img.Bounds().Max.X
159	maxy := img.Bounds().Max.Y
160	y := rnd(maxy/3, maxy-maxy/3)
161	amplitude := rndf(5, 20)
162	period := rndf(80, 180)
163	dx := 2.0 * math.Pi / period
164	for x := 0; x < maxx; x++ {
165		xo := amplitude * math.Cos(float64(y)*dx)
166		yo := amplitude * math.Sin(float64(x)*dx)
167		for yn := 0; yn < img.dotSize; yn++ {
168			r := rnd(0, img.dotSize)
169			img.drawCircle(img.primaryColor, x+int(xo), y+int(yo)+(yn*img.dotSize), r/2)
170		}
171	}
172}
173
174func (img *Image) drawDigit(digit []byte, x, y int) {
175	skf := rndf(-maxSkew, maxSkew)
176	xs := float64(x)
177	r := img.dotSize / 2
178	y += rnd(-r, r)
179	for yy := 0; yy < fontHeight; yy++ {
180		for xx := 0; xx < fontWidth; xx++ {
181			if digit[yy*fontWidth+xx] != blackChar {
182				continue
183			}
184			ox := x + xx*img.dotSize
185			oy := y + yy*img.dotSize
186			img.drawCircle(img.primaryColor, ox, oy, r)
187		}
188		xs += skf
189		x = int(xs)
190	}
191}
192
193func (img *Image) distort(amplude float64, period float64) {
194	w := img.Bounds().Max.X
195	h := img.Bounds().Max.Y
196
197	oldImg := img.NRGBA
198	newImg := image.NewNRGBA(w, h)
199
200	dx := 2.0 * math.Pi / period
201	for x := 0; x < w; x++ {
202		for y := 0; y < h; y++ {
203			ox := amplude * math.Sin(float64(y)*dx)
204			oy := amplude * math.Cos(float64(x)*dx)
205			newImg.Set(x, y, oldImg.At(x+int(ox), y+int(oy)))
206		}
207	}
208	img.NRGBA = newImg
209}
210
211func setRandomBrightness(c *image.NRGBAColor, max uint8) {
212	minc := min3(c.R, c.G, c.B)
213	maxc := max3(c.R, c.G, c.B)
214	if maxc > max {
215		return
216	}
217	n := rand.Intn(int(max-maxc)) - int(minc)
218	c.R = uint8(int(c.R) + n)
219	c.G = uint8(int(c.G) + n)
220	c.B = uint8(int(c.B) + n)
221}
222
223func min3(x, y, z uint8) (o uint8) {
224	o = x
225	if y < o {
226		o = y
227	}
228	if z < o {
229		o = z
230	}
231	return
232}
233
234func max3(x, y, z uint8) (o uint8) {
235	o = x
236	if y > o {
237		o = y
238	}
239	if z > o {
240		o = z
241	}
242	return
243}
244
245// rnd returns a random number in range [from, to].
246func rnd(from, to int) int {
247	return rand.Intn(to+1-from) + from
248}