all repos — captcha @ b1a072665d48250038d0fcbb63337052af37fb47

Go package captcha implements generation and verification of image and audio CAPTCHAs.

image.go (view raw)

  1// Copyright 2011 Dmitry Chestnykh. All rights reserved.
  2// Use of this source code is governed by a MIT-style
  3// license that can be found in the LICENSE file.
  4
  5package captcha
  6
  7import (
  8	"image"
  9	"image/color"
 10	"image/png"
 11	"io"
 12	"math"
 13	"math/rand"
 14)
 15
 16const (
 17	// Standard width and height of a captcha image.
 18	StdWidth  = 240
 19	StdHeight = 80
 20	// Maximum absolute skew factor of a single digit.
 21	maxSkew = 0.7
 22	// Number of background circles.
 23	circleCount = 20
 24)
 25
 26type Image struct {
 27	*image.Paletted
 28	numWidth  int
 29	numHeight int
 30	dotSize   int
 31}
 32
 33func randomPalette() color.Palette {
 34	p := make([]color.Color, circleCount+1)
 35	// Transparent color.
 36	p[0] = color.RGBA{0xFF, 0xFF, 0xFF, 0x00}
 37	// Primary color.
 38	prim := color.RGBA{
 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	m := new(Image)
 56	m.Paletted = image.NewPaletted(image.Rect(0, 0, width, height), randomPalette())
 57	m.calculateSizes(width, height, len(digits))
 58	// Randomly position captcha inside the image.
 59	maxx := width - (m.numWidth+m.dotSize)*len(digits) - m.dotSize
 60	maxy := height - m.numHeight - m.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		m.drawDigit(font[n], x, y)
 72		x += m.numWidth + m.dotSize
 73	}
 74	// Draw strike-through line.
 75	m.strikeThrough()
 76	// Apply wave distortion.
 77	m.distort(rndf(5, 10), rndf(100, 200))
 78	// Fill image with random circles.
 79	m.fillWithCircles(circleCount, m.dotSize)
 80	return m
 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 (m *Image) WriteTo(w io.Writer) (int64, error) {
 89	return 0, png.Encode(w, m.Paletted)
 90}
 91
 92func (m *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	m.dotSize = int(nh / fh)
120	// Save everything, making the actual width smaller by 1 dot to account
121	// for spacing between digits.
122	m.numWidth = int(nw) - m.dotSize
123	m.numHeight = int(nh)
124}
125
126func (m *Image) drawHorizLine(fromX, toX, y int, colorIdx uint8) {
127	for x := fromX; x <= toX; x++ {
128		m.SetColorIndex(x, y, colorIdx)
129	}
130}
131
132func (m *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	m.SetColorIndex(x, y+radius, colorIdx)
140	m.SetColorIndex(x, y-radius, colorIdx)
141	m.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		m.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
153		m.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
154		m.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
155		m.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
156	}
157}
158
159func (m *Image) fillWithCircles(n, maxradius int) {
160	maxx := m.Bounds().Max.X
161	maxy := m.Bounds().Max.Y
162	for i := 0; i < n; i++ {
163		colorIdx := uint8(rnd(1, circleCount-1))
164		r := rnd(1, maxradius)
165		m.drawCircle(rnd(r, maxx-r), rnd(r, maxy-r), r, colorIdx)
166	}
167}
168
169func (m *Image) strikeThrough() {
170	maxx := m.Bounds().Max.X
171	maxy := m.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 < m.dotSize; yn++ {
180			r := rnd(0, m.dotSize)
181			m.drawCircle(x+int(xo), y+int(yo)+(yn*m.dotSize), r/2, 1)
182		}
183	}
184}
185
186func (m *Image) drawDigit(digit []byte, x, y int) {
187	skf := rndf(-maxSkew, maxSkew)
188	xs := float64(x)
189	r := m.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			m.drawCircle(x+xo*m.dotSize, y+yo*m.dotSize, r, 1)
197		}
198		xs += skf
199		x = int(xs)
200	}
201}
202
203func (m *Image) distort(amplude float64, period float64) {
204	w := m.Bounds().Max.X
205	h := m.Bounds().Max.Y
206
207	oldm := m.Paletted
208	newm := image.NewPaletted(image.Rect(0, 0, w, h), oldm.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			newm.SetColorIndex(x, y, oldm.ColorIndexAt(x+int(xo), y+int(yo)))
216		}
217	}
218	m.Paletted = newm
219}
220
221func randomBrightness(c color.RGBA, max uint8) color.RGBA {
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 color.RGBA{
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}