image.go 6.1 KB

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