image.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package captcha
  2. import (
  3. "image"
  4. "image/png"
  5. "io"
  6. "math"
  7. "os"
  8. "rand"
  9. )
  10. const (
  11. // Standard width and height of a captcha image.
  12. StdWidth = 240
  13. StdHeight = 80
  14. // Maximum absolute skew factor of a single digit.
  15. maxSkew = 0.7
  16. // Number of background circles.
  17. circleCount = 20
  18. )
  19. type Image struct {
  20. *image.Paletted
  21. numWidth int
  22. numHeight int
  23. dotSize int
  24. }
  25. func randomPalette() image.PalettedColorModel {
  26. p := make([]image.Color, circleCount+1)
  27. // Transparent color.
  28. // TODO(dchest). Currently it's white, not transparent, because PNG
  29. // encoder doesn't support paletted images with alpha channel.
  30. // Submitted CL: http://codereview.appspot.com/4432078 Change alpha to
  31. // 0x00 once it's accepted.
  32. p[0] = image.RGBAColor{0xFF, 0xFF, 0xFF, 0xFF}
  33. // Primary color.
  34. prim := image.RGBAColor{
  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(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. // BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
  78. // method returns 0 instead of the actual bytes written because png.Encode
  79. // doesn't report this.
  80. // WriteTo writes captcha image in PNG format into the given writer.
  81. func (m *Image) WriteTo(w io.Writer) (int64, os.Error) {
  82. return 0, png.Encode(w, m.Paletted)
  83. }
  84. func (m *Image) calculateSizes(width, height, ncount int) {
  85. // Goal: fit all digits inside the image.
  86. var border int
  87. if width > height {
  88. border = height / 4
  89. } else {
  90. border = width / 4
  91. }
  92. // Convert everything to floats for calculations.
  93. w := float64(width - border*2)
  94. h := float64(height - border*2)
  95. // fw takes into account 1-dot spacing between digits.
  96. fw := float64(fontWidth + 1)
  97. fh := float64(fontHeight)
  98. nc := float64(ncount)
  99. // Calculate the width of a single digit taking into account only the
  100. // width of the image.
  101. nw := w / nc
  102. // Calculate the height of a digit from this width.
  103. nh := nw * fh / fw
  104. // Digit too high?
  105. if nh > h {
  106. // Fit digits based on height.
  107. nh = h
  108. nw = fw / fh * nh
  109. }
  110. // Calculate dot size.
  111. m.dotSize = int(nh / fh)
  112. // Save everything, making the actual width smaller by 1 dot to account
  113. // for spacing between digits.
  114. m.numWidth = int(nw) - m.dotSize
  115. m.numHeight = int(nh)
  116. }
  117. func (m *Image) drawHorizLine(fromX, toX, y int, colorIdx uint8) {
  118. for x := fromX; x <= toX; x++ {
  119. m.SetColorIndex(x, y, colorIdx)
  120. }
  121. }
  122. func (m *Image) drawCircle(x, y, radius int, colorIdx uint8) {
  123. f := 1 - radius
  124. dfx := 1
  125. dfy := -2 * radius
  126. xo := 0
  127. yo := radius
  128. m.SetColorIndex(x, y+radius, colorIdx)
  129. m.SetColorIndex(x, y-radius, colorIdx)
  130. m.drawHorizLine(x-radius, x+radius, y, colorIdx)
  131. for xo < yo {
  132. if f >= 0 {
  133. yo--
  134. dfy += 2
  135. f += dfy
  136. }
  137. xo++
  138. dfx += 2
  139. f += dfx
  140. m.drawHorizLine(x-xo, x+xo, y+yo, colorIdx)
  141. m.drawHorizLine(x-xo, x+xo, y-yo, colorIdx)
  142. m.drawHorizLine(x-yo, x+yo, y+xo, colorIdx)
  143. m.drawHorizLine(x-yo, x+yo, y-xo, colorIdx)
  144. }
  145. }
  146. func (m *Image) fillWithCircles(n, maxradius int) {
  147. maxx := m.Bounds().Max.X
  148. maxy := m.Bounds().Max.Y
  149. for i := 0; i < n; i++ {
  150. colorIdx := uint8(rnd(1, circleCount-1))
  151. r := rnd(1, maxradius)
  152. m.drawCircle(rnd(r, maxx-r), rnd(r, maxy-r), r, colorIdx)
  153. }
  154. }
  155. func (m *Image) strikeThrough() {
  156. maxx := m.Bounds().Max.X
  157. maxy := m.Bounds().Max.Y
  158. y := rnd(maxy/3, maxy-maxy/3)
  159. amplitude := rndf(5, 20)
  160. period := rndf(80, 180)
  161. dx := 2.0 * math.Pi / period
  162. for x := 0; x < maxx; x++ {
  163. xo := amplitude * math.Cos(float64(y)*dx)
  164. yo := amplitude * math.Sin(float64(x)*dx)
  165. for yn := 0; yn < m.dotSize; yn++ {
  166. r := rnd(0, m.dotSize)
  167. m.drawCircle(x+int(xo), y+int(yo)+(yn*m.dotSize), r/2, 1)
  168. }
  169. }
  170. }
  171. func (m *Image) drawDigit(digit []byte, x, y int) {
  172. skf := rndf(-maxSkew, maxSkew)
  173. xs := float64(x)
  174. r := m.dotSize / 2
  175. y += rnd(-r, r)
  176. for yo := 0; yo < fontHeight; yo++ {
  177. for xo := 0; xo < fontWidth; xo++ {
  178. if digit[yo*fontWidth+xo] != blackChar {
  179. continue
  180. }
  181. m.drawCircle(x+xo*m.dotSize, y+yo*m.dotSize, r, 1)
  182. }
  183. xs += skf
  184. x = int(xs)
  185. }
  186. }
  187. func (m *Image) distort(amplude float64, period float64) {
  188. w := m.Bounds().Max.X
  189. h := m.Bounds().Max.Y
  190. oldm := m.Paletted
  191. newm := image.NewPaletted(w, h, oldm.Palette)
  192. dx := 2.0 * math.Pi / period
  193. for x := 0; x < w; x++ {
  194. for y := 0; y < h; y++ {
  195. xo := amplude * math.Sin(float64(y)*dx)
  196. yo := amplude * math.Cos(float64(x)*dx)
  197. newm.SetColorIndex(x, y, oldm.ColorIndexAt(x+int(xo), y+int(yo)))
  198. }
  199. }
  200. m.Paletted = newm
  201. }
  202. func randomBrightness(c image.RGBAColor, max uint8) image.RGBAColor {
  203. minc := min3(c.R, c.G, c.B)
  204. maxc := max3(c.R, c.G, c.B)
  205. if maxc > max {
  206. return c
  207. }
  208. n := rand.Intn(int(max-maxc)) - int(minc)
  209. return image.RGBAColor{
  210. uint8(int(c.R) + n),
  211. uint8(int(c.G) + n),
  212. uint8(int(c.B) + n),
  213. uint8(c.A),
  214. }
  215. }
  216. func min3(x, y, z uint8) (m uint8) {
  217. m = x
  218. if y < m {
  219. m = y
  220. }
  221. if z < m {
  222. m = z
  223. }
  224. return
  225. }
  226. func max3(x, y, z uint8) (m uint8) {
  227. m = x
  228. if y > m {
  229. m = y
  230. }
  231. if z > m {
  232. m = z
  233. }
  234. return
  235. }