image.go 6.2 KB

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