image.go 6.0 KB

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