image.go 5.6 KB

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