image.go 5.9 KB

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