image.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package captcha
  2. import (
  3. "image"
  4. "image/png"
  5. "io"
  6. "math"
  7. "os"
  8. "rand"
  9. "time"
  10. )
  11. const (
  12. // Standard width and height of a captcha image.
  13. StdWidth = 240
  14. StdHeight = 80
  15. // Maximum absolute skew factor of a single digit.
  16. maxSkew = 0.7
  17. )
  18. type Image struct {
  19. *image.NRGBA
  20. primaryColor image.NRGBAColor
  21. numWidth int
  22. numHeight int
  23. dotSize int
  24. }
  25. func init() {
  26. rand.Seed(time.Seconds())
  27. }
  28. // NewImage returns a new captcha image of the given width and height with the
  29. // given digits, where each digit must be in range 0-9.
  30. func NewImage(digits []byte, width, height int) *Image {
  31. img := new(Image)
  32. img.NRGBA = image.NewNRGBA(width, height)
  33. img.primaryColor = image.NRGBAColor{
  34. uint8(rand.Intn(129)),
  35. uint8(rand.Intn(129)),
  36. uint8(rand.Intn(129)),
  37. 0xFF,
  38. }
  39. img.calculateSizes(width, height, len(digits))
  40. // Randomly position captcha inside the image.
  41. maxx := width - (img.numWidth+img.dotSize)*len(digits) - img.dotSize
  42. maxy := height - img.numHeight - img.dotSize*2
  43. var border int
  44. if width > height {
  45. border = height / 5
  46. } else {
  47. border = width / 5
  48. }
  49. x := rnd(border, maxx-border)
  50. y := rnd(border, maxy-border)
  51. // Draw digits.
  52. for _, n := range digits {
  53. img.drawDigit(font[n], x, y)
  54. x += img.numWidth + img.dotSize
  55. }
  56. // Draw strike-through line.
  57. img.strikeThrough()
  58. // Apply wave distortion.
  59. img.distort(rndf(5, 10), rndf(100, 200))
  60. // Fill image with random circles.
  61. img.fillWithCircles(20, img.dotSize)
  62. return img
  63. }
  64. // BUG(dchest): While Image conforms to io.WriterTo interface, its WriteTo
  65. // method returns 0 instead of the actual bytes written because png.Encode
  66. // doesn't report this.
  67. // WriteTo writes captcha image in PNG format into the given writer.
  68. func (img *Image) WriteTo(w io.Writer) (int64, os.Error) {
  69. return 0, png.Encode(w, img)
  70. }
  71. func (img *Image) calculateSizes(width, height, ncount int) {
  72. // Goal: fit all digits inside the image.
  73. var border int
  74. if width > height {
  75. border = height / 4
  76. } else {
  77. border = width / 4
  78. }
  79. // Convert everything to floats for calculations.
  80. w := float64(width - border*2)
  81. h := float64(height - border*2)
  82. // fw takes into account 1-dot spacing between digits.
  83. fw := float64(fontWidth + 1)
  84. fh := float64(fontHeight)
  85. nc := float64(ncount)
  86. // Calculate the width of a single digit taking into account only the
  87. // width of the image.
  88. nw := w / nc
  89. // Calculate the height of a digit from this width.
  90. nh := nw * fh / fw
  91. // Digit too high?
  92. if nh > h {
  93. // Fit digits based on height.
  94. nh = h
  95. nw = fw / fh * nh
  96. }
  97. // Calculate dot size.
  98. img.dotSize = int(nh / fh)
  99. // Save everything, making the actual width smaller by 1 dot to account
  100. // for spacing between digits.
  101. img.numWidth = int(nw) - img.dotSize
  102. img.numHeight = int(nh)
  103. }
  104. func (img *Image) drawHorizLine(color image.Color, fromX, toX, y int) {
  105. for x := fromX; x <= toX; x++ {
  106. img.Set(x, y, color)
  107. }
  108. }
  109. func (img *Image) drawCircle(color image.Color, x, y, radius int) {
  110. f := 1 - radius
  111. dfx := 1
  112. dfy := -2 * radius
  113. xx := 0
  114. yy := radius
  115. img.Set(x, y+radius, color)
  116. img.Set(x, y-radius, color)
  117. img.drawHorizLine(color, x-radius, x+radius, y)
  118. for xx < yy {
  119. if f >= 0 {
  120. yy--
  121. dfy += 2
  122. f += dfy
  123. }
  124. xx++
  125. dfx += 2
  126. f += dfx
  127. img.drawHorizLine(color, x-xx, x+xx, y+yy)
  128. img.drawHorizLine(color, x-xx, x+xx, y-yy)
  129. img.drawHorizLine(color, x-yy, x+yy, y+xx)
  130. img.drawHorizLine(color, x-yy, x+yy, y-xx)
  131. }
  132. }
  133. func (img *Image) fillWithCircles(n, maxradius int) {
  134. color := img.primaryColor
  135. maxx := img.Bounds().Max.X
  136. maxy := img.Bounds().Max.Y
  137. for i := 0; i < n; i++ {
  138. setRandomBrightness(&color, 255)
  139. r := rnd(1, maxradius)
  140. img.drawCircle(color, rnd(r, maxx-r), rnd(r, maxy-r), r)
  141. }
  142. }
  143. func (img *Image) strikeThrough() {
  144. maxx := img.Bounds().Max.X
  145. maxy := img.Bounds().Max.Y
  146. y := rnd(maxy/3, maxy-maxy/3)
  147. amplitude := rndf(5, 20)
  148. period := rndf(80, 180)
  149. dx := 2.0 * math.Pi / period
  150. for x := 0; x < maxx; x++ {
  151. xo := amplitude * math.Cos(float64(y)*dx)
  152. yo := amplitude * math.Sin(float64(x)*dx)
  153. for yn := 0; yn < img.dotSize; yn++ {
  154. r := rnd(0, img.dotSize)
  155. img.drawCircle(img.primaryColor, x+int(xo), y+int(yo)+(yn*img.dotSize), r/2)
  156. }
  157. }
  158. }
  159. func (img *Image) drawDigit(digit []byte, x, y int) {
  160. skf := rndf(-maxSkew, maxSkew)
  161. xs := float64(x)
  162. r := img.dotSize / 2
  163. y += rnd(-r, r)
  164. for yy := 0; yy < fontHeight; yy++ {
  165. for xx := 0; xx < fontWidth; xx++ {
  166. if digit[yy*fontWidth+xx] != blackChar {
  167. continue
  168. }
  169. ox := x + xx*img.dotSize
  170. oy := y + yy*img.dotSize
  171. img.drawCircle(img.primaryColor, ox, oy, r)
  172. }
  173. xs += skf
  174. x = int(xs)
  175. }
  176. }
  177. func (img *Image) distort(amplude float64, period float64) {
  178. w := img.Bounds().Max.X
  179. h := img.Bounds().Max.Y
  180. oldImg := img.NRGBA
  181. newImg := image.NewNRGBA(w, h)
  182. dx := 2.0 * math.Pi / period
  183. for x := 0; x < w; x++ {
  184. for y := 0; y < h; y++ {
  185. ox := amplude * math.Sin(float64(y)*dx)
  186. oy := amplude * math.Cos(float64(x)*dx)
  187. newImg.Set(x, y, oldImg.At(x+int(ox), y+int(oy)))
  188. }
  189. }
  190. img.NRGBA = newImg
  191. }
  192. func setRandomBrightness(c *image.NRGBAColor, max uint8) {
  193. minc := min3(c.R, c.G, c.B)
  194. maxc := max3(c.R, c.G, c.B)
  195. if maxc > max {
  196. return
  197. }
  198. n := rand.Intn(int(max-maxc)) - int(minc)
  199. c.R = uint8(int(c.R) + n)
  200. c.G = uint8(int(c.G) + n)
  201. c.B = uint8(int(c.B) + n)
  202. }
  203. func min3(x, y, z uint8) (o uint8) {
  204. o = x
  205. if y < o {
  206. o = y
  207. }
  208. if z < o {
  209. o = z
  210. }
  211. return
  212. }
  213. func max3(x, y, z uint8) (o uint8) {
  214. o = x
  215. if y > o {
  216. o = y
  217. }
  218. if z > o {
  219. o = z
  220. }
  221. return
  222. }
  223. // rnd returns a random number in range [from, to].
  224. func rnd(from, to int) int {
  225. return rand.Intn(to+1-from) + from
  226. }