image.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. "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. }
  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(randIntn(129)),
  35. uint8(randIntn(129)),
  36. uint8(randIntn(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 := randInt(border, maxx-border)
  62. y := randInt(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(randFloat(5, 10), randFloat(100, 200))
  72. // Fill image with random circles.
  73. m.fillWithCircles(circleCount, m.dotSize)
  74. return m
  75. }
  76. // encodedPNG encodes an image to PNG and returns
  77. // the result as a byte slice.
  78. func (m *Image) encodedPNG() []byte {
  79. var buf bytes.Buffer
  80. if err := png.Encode(&buf, m.Paletted); err != nil {
  81. panic(err.Error())
  82. }
  83. return buf.Bytes()
  84. }
  85. // WriteTo writes captcha image in PNG format into the given writer.
  86. func (m *Image) WriteTo(w io.Writer) (int64, error) {
  87. n, err := w.Write(m.encodedPNG())
  88. return int64(n), err
  89. }
  90. func (m *Image) calculateSizes(width, height, ncount int) {
  91. // Goal: fit all digits inside the image.
  92. var border int
  93. if width > height {
  94. border = height / 4
  95. } else {
  96. border = width / 4
  97. }
  98. // Convert everything to floats for calculations.
  99. w := float64(width - border*2)
  100. h := float64(height - border*2)
  101. // fw takes into account 1-dot spacing between digits.
  102. fw := float64(fontWidth + 1)
  103. fh := float64(fontHeight)
  104. nc := float64(ncount)
  105. // Calculate the width of a single digit taking into account only the
  106. // width of the image.
  107. nw := w / nc
  108. // Calculate the height of a digit from this width.
  109. nh := nw * fh / fw
  110. // Digit too high?
  111. if nh > h {
  112. // Fit digits based on height.
  113. nh = h
  114. nw = fw / fh * nh
  115. }
  116. // Calculate dot size.
  117. m.dotSize = int(nh / fh)
  118. // Save everything, making the actual width smaller by 1 dot to account
  119. // for spacing between digits.
  120. m.numWidth = int(nw) - m.dotSize
  121. m.numHeight = int(nh)
  122. }
  123. func (m *Image) drawHorizLine(fromX, toX, y int, colorIdx uint8) {
  124. for x := fromX; x <= toX; x++ {
  125. m.SetColorIndex(x, y, colorIdx)
  126. }
  127. }
  128. func (m *Image) drawCircle(x, y, radius int, colorIdx uint8) {
  129. f := 1 - radius
  130. dfx := 1
  131. dfy := -2 * radius
  132. xo := 0
  133. yo := radius
  134. m.SetColorIndex(x, y+radius, colorIdx)
  135. m.SetColorIndex(x, y-radius, colorIdx)
  136. m.drawHorizLine(x-radius, x+radius, y, colorIdx)
  137. for xo < yo {
  138. if f >= 0 {
  139. yo--
  140. dfy += 2
  141. f += dfy
  142. }
  143. xo++
  144. dfx += 2
  145. f += dfx
  146. m.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
  147. m.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
  148. m.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
  149. m.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
  150. }
  151. }
  152. func (m *Image) fillWithCircles(n, maxradius int) {
  153. maxx := m.Bounds().Max.X
  154. maxy := m.Bounds().Max.Y
  155. for i := 0; i < n; i++ {
  156. colorIdx := uint8(randInt(1, circleCount-1))
  157. r := randInt(1, maxradius)
  158. m.drawCircle(randInt(r, maxx-r), randInt(r, maxy-r), r, colorIdx)
  159. }
  160. }
  161. func (m *Image) strikeThrough() {
  162. maxx := m.Bounds().Max.X
  163. maxy := m.Bounds().Max.Y
  164. y := randInt(maxy/3, maxy-maxy/3)
  165. amplitude := randFloat(5, 20)
  166. period := randFloat(80, 180)
  167. dx := 2.0 * math.Pi / period
  168. for x := 0; x < maxx; x++ {
  169. xo := amplitude * math.Cos(float64(y)*dx)
  170. yo := amplitude * math.Sin(float64(x)*dx)
  171. for yn := 0; yn < m.dotSize; yn++ {
  172. r := randInt(0, m.dotSize)
  173. m.drawCircle(x+int(xo), y+int(yo)+(yn*m.dotSize), r/2, 1)
  174. }
  175. }
  176. }
  177. func (m *Image) drawDigit(digit []byte, x, y int) {
  178. skf := randFloat(-maxSkew, maxSkew)
  179. xs := float64(x)
  180. r := m.dotSize / 2
  181. y += randInt(-r, r)
  182. for yo := 0; yo < fontHeight; yo++ {
  183. for xo := 0; xo < fontWidth; xo++ {
  184. if digit[yo*fontWidth+xo] != blackChar {
  185. continue
  186. }
  187. m.drawCircle(x+xo*m.dotSize, y+yo*m.dotSize, r, 1)
  188. }
  189. xs += skf
  190. x = int(xs)
  191. }
  192. }
  193. func (m *Image) distort(amplude float64, period float64) {
  194. w := m.Bounds().Max.X
  195. h := m.Bounds().Max.Y
  196. oldm := m.Paletted
  197. newm := image.NewPaletted(image.Rect(0, 0, w, h), oldm.Palette)
  198. dx := 2.0 * math.Pi / period
  199. for x := 0; x < w; x++ {
  200. for y := 0; y < h; y++ {
  201. xo := amplude * math.Sin(float64(y)*dx)
  202. yo := amplude * math.Cos(float64(x)*dx)
  203. newm.SetColorIndex(x, y, oldm.ColorIndexAt(x+int(xo), y+int(yo)))
  204. }
  205. }
  206. m.Paletted = newm
  207. }
  208. func randomBrightness(c color.RGBA, max uint8) color.RGBA {
  209. minc := min3(c.R, c.G, c.B)
  210. maxc := max3(c.R, c.G, c.B)
  211. if maxc > max {
  212. return c
  213. }
  214. n := randIntn(int(max-maxc)) - int(minc)
  215. return color.RGBA{
  216. uint8(int(c.R) + n),
  217. uint8(int(c.G) + n),
  218. uint8(int(c.B) + n),
  219. uint8(c.A),
  220. }
  221. }
  222. func min3(x, y, z uint8) (m uint8) {
  223. m = x
  224. if y < m {
  225. m = y
  226. }
  227. if z < m {
  228. m = z
  229. }
  230. return
  231. }
  232. func max3(x, y, z uint8) (m uint8) {
  233. m = x
  234. if y > m {
  235. m = y
  236. }
  237. if z > m {
  238. m = z
  239. }
  240. return
  241. }