image.go 5.8 KB

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