all repos — captcha @ c5afad979e03412a52e918c08721999ff477cff6

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
 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	// Draw background (20 random circles of random brightness).
 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	height := img.dotSize
159	maxx := img.Bounds().Max.X
160	maxy := img.Bounds().Max.Y
161	y := rnd(maxy/3, maxy-maxy/3)
162	amplitude := rndf(5, 20)
163	period := rndf(80, 180)
164	for x := 0; x < maxx; x++ {
165		xo := amplitude * math.Cos(2.0*math.Pi*float64(y)/period)
166		yo := amplitude * math.Sin(2.0*math.Pi*float64(x)/period)
167		for yn := 0; yn < height; 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			// Introduce random variations.
185			ox := x + (xx * img.dotSize) + rnd(0, r/2)
186			oy := y + (yy * img.dotSize) + rnd(0, r/2)
187
188			img.drawCircle(img.primaryColor, ox, oy, r)
189		}
190		xs += skf
191		x = int(xs)
192	}
193}
194
195func (img *Image) distort(amplude float64, period float64) {
196	w := img.Bounds().Max.X
197	h := img.Bounds().Max.Y
198
199	oldImg := img.NRGBA
200	newImg := image.NewNRGBA(w, h)
201
202	for x := 0; x < w; x++ {
203		for y := 0; y < h; y++ {
204			ox := amplude * math.Sin(2.0*math.Pi*float64(y)/period)
205			oy := amplude * math.Cos(2.0*math.Pi*float64(x)/period)
206			newImg.Set(x, y, oldImg.At(x + int(ox), y + int(oy)))
207		}
208	}
209	img.NRGBA = newImg
210}
211
212func setRandomBrightness(c *image.NRGBAColor, max uint8) {
213	minc := min3(c.R, c.G, c.B)
214	maxc := max3(c.R, c.G, c.B)
215	if maxc > max {
216		return
217	}
218	n := rand.Intn(int(max-maxc)) - int(minc)
219	c.R = uint8(int(c.R) + n)
220	c.G = uint8(int(c.G) + n)
221	c.B = uint8(int(c.B) + n)
222}
223
224func min3(x, y, z uint8) (o uint8) {
225	o = x
226	if y < o {
227		o = y
228	}
229	if z < o {
230		o = z
231	}
232	return
233}
234
235func max3(x, y, z uint8) (o uint8) {
236	o = x
237	if y > o {
238		o = y
239	}
240	if z > o {
241		o = z
242	}
243	return
244}
245
246// rnd returns a random number in range [from, to].
247func rnd(from, to int) int {
248	return rand.Intn(to+1-from) + from
249}