image.go 6.2 KB

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