image.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. // Save everything, making the actual width smaller by 1 dot to account
  122. // for spacing between digits.
  123. m.numWidth = int(nw) - m.dotSize
  124. m.numHeight = int(nh)
  125. }
  126. func (m *Image) drawHorizLine(fromX, toX, y int, colorIdx uint8) {
  127. for x := fromX; x <= toX; x++ {
  128. m.SetColorIndex(x, y, colorIdx)
  129. }
  130. }
  131. func (m *Image) drawCircle(x, y, radius int, colorIdx uint8) {
  132. f := 1 - radius
  133. dfx := 1
  134. dfy := -2 * radius
  135. xo := 0
  136. yo := radius
  137. m.SetColorIndex(x, y+radius, colorIdx)
  138. m.SetColorIndex(x, y-radius, colorIdx)
  139. m.drawHorizLine(x-radius, x+radius, y, colorIdx)
  140. for xo < yo {
  141. if f >= 0 {
  142. yo--
  143. dfy += 2
  144. f += dfy
  145. }
  146. xo++
  147. dfx += 2
  148. f += dfx
  149. m.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
  150. m.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
  151. m.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
  152. m.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
  153. }
  154. }
  155. func (m *Image) fillWithCircles(n, maxradius int) {
  156. maxx := m.Bounds().Max.X
  157. maxy := m.Bounds().Max.Y
  158. for i := 0; i < n; i++ {
  159. colorIdx := uint8(m.rng.Int(1, circleCount-1))
  160. r := m.rng.Int(1, maxradius)
  161. m.drawCircle(m.rng.Int(r, maxx-r), m.rng.Int(r, maxy-r), r, colorIdx)
  162. }
  163. }
  164. func (m *Image) strikeThrough() {
  165. maxx := m.Bounds().Max.X
  166. maxy := m.Bounds().Max.Y
  167. y := m.rng.Int(maxy/3, maxy-maxy/3)
  168. amplitude := m.rng.Float(5, 20)
  169. period := m.rng.Float(80, 180)
  170. dx := 2.0 * math.Pi / period
  171. for x := 0; x < maxx; x++ {
  172. xo := amplitude * math.Cos(float64(y)*dx)
  173. yo := amplitude * math.Sin(float64(x)*dx)
  174. for yn := 0; yn < m.dotSize; yn++ {
  175. r := m.rng.Int(0, m.dotSize)
  176. m.drawCircle(x+int(xo), y+int(yo)+(yn*m.dotSize), r/2, 1)
  177. }
  178. }
  179. }
  180. func (m *Image) drawDigit(digit []byte, x, y int) {
  181. skf := m.rng.Float(-maxSkew, maxSkew)
  182. xs := float64(x)
  183. r := m.dotSize / 2
  184. y += m.rng.Int(-r, r)
  185. for yo := 0; yo < fontHeight; yo++ {
  186. for xo := 0; xo < fontWidth; xo++ {
  187. if digit[yo*fontWidth+xo] != blackChar {
  188. continue
  189. }
  190. m.drawCircle(x+xo*m.dotSize, y+yo*m.dotSize, r, 1)
  191. }
  192. xs += skf
  193. x = int(xs)
  194. }
  195. }
  196. func (m *Image) distort(amplude float64, period float64) {
  197. w := m.Bounds().Max.X
  198. h := m.Bounds().Max.Y
  199. oldm := m.Paletted
  200. newm := image.NewPaletted(image.Rect(0, 0, w, h), oldm.Palette)
  201. dx := 2.0 * math.Pi / period
  202. for x := 0; x < w; x++ {
  203. for y := 0; y < h; y++ {
  204. xo := amplude * math.Sin(float64(y)*dx)
  205. yo := amplude * math.Cos(float64(x)*dx)
  206. newm.SetColorIndex(x, y, oldm.ColorIndexAt(x+int(xo), y+int(yo)))
  207. }
  208. }
  209. m.Paletted = newm
  210. }
  211. func (m *Image) randomBrightness(c color.RGBA, max uint8) color.RGBA {
  212. minc := min3(c.R, c.G, c.B)
  213. maxc := max3(c.R, c.G, c.B)
  214. if maxc > max {
  215. return c
  216. }
  217. n := m.rng.Intn(int(max-maxc)) - int(minc)
  218. return color.RGBA{
  219. uint8(int(c.R) + n),
  220. uint8(int(c.G) + n),
  221. uint8(int(c.B) + n),
  222. uint8(c.A),
  223. }
  224. }
  225. func min3(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. }
  235. func max3(x, y, z uint8) (m uint8) {
  236. m = x
  237. if y > m {
  238. m = y
  239. }
  240. if z > m {
  241. m = z
  242. }
  243. return
  244. }