image.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. package captcha
  2. import (
  3. "image"
  4. "image/png"
  5. "io"
  6. "os"
  7. "rand"
  8. "time"
  9. )
  10. const (
  11. // Standard width and height for captcha image
  12. StdWidth = 300
  13. StdHeight = 80
  14. maxSkew = 2
  15. )
  16. type Image struct {
  17. *image.NRGBA
  18. primaryColor image.NRGBAColor
  19. numWidth int
  20. numHeight int
  21. dotSize int
  22. }
  23. func init() {
  24. rand.Seed(time.Seconds())
  25. }
  26. // NewImage returns a new captcha image of the given width and height with the
  27. // given slice of numbers, where each number must be in range 0-9.
  28. func NewImage(numbers []byte, width, height int) *Image {
  29. img := new(Image)
  30. img.NRGBA = image.NewNRGBA(width, height)
  31. img.primaryColor = image.NRGBAColor{
  32. uint8(rand.Intn(129)),
  33. uint8(rand.Intn(129)),
  34. uint8(rand.Intn(129)),
  35. 0xFF,
  36. }
  37. // Calculate sizes
  38. img.calculateSizes(width, height, len(numbers))
  39. // Draw background (10 random circles of random brightness)
  40. img.fillWithCircles(10, img.dotSize)
  41. // Randomly position captcha inside the image
  42. maxx := width - (img.numWidth+img.dotSize)*len(numbers) - img.dotSize
  43. maxy := height - img.numHeight - img.dotSize*2
  44. x := rnd(img.dotSize*2, maxx)
  45. y := rnd(img.dotSize*2, maxy)
  46. // Draw numbers
  47. for _, n := range numbers {
  48. img.drawNumber(font[n], x, y)
  49. x += img.numWidth + img.dotSize
  50. }
  51. // Draw strike-through line
  52. img.strikeThrough()
  53. return img
  54. }
  55. // NewRandomImage generates a sequence of random numbers with the given length,
  56. // and returns a new captcha image of the given width and height with generated
  57. // numbers printed on it, and the sequence of numbers itself.
  58. func NewRandomImage(length, width, height int) (img *Image, numbers []byte) {
  59. numbers = randomNumbers(length)
  60. img = NewImage(numbers, width, height)
  61. return
  62. }
  63. // WriteTo writes captcha image in PNG format into the given writer.
  64. //
  65. // Bug: while Image conforms to io.WriterTo interface, this function returns 0
  66. // instead of the actual bytes written because png.Encode doesn't report this.
  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 numbers inside the image.
  72. var border int
  73. if width > height {
  74. border = height / 5
  75. } else {
  76. border = width / 5
  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 numbers
  82. fw := float64(fontWidth) + 1
  83. fh := float64(fontHeight)
  84. nc := float64(ncount)
  85. // Calculate the width of a single number taking into account only the
  86. // width of the image
  87. nw := w / nc
  88. // Calculate the height of a number from this width
  89. nh := nw * fh / fw
  90. // Number height too large?
  91. if nh > h {
  92. // Fit numbers 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 numbers
  100. img.numWidth = int(nw)
  101. img.numHeight = int(nh) - img.dotSize
  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. r := 0
  144. maxx := img.Bounds().Max.X
  145. maxy := img.Bounds().Max.Y
  146. y := rnd(maxy/3, maxy-maxy/3)
  147. for x := 0; x < maxx; x += r {
  148. r = rnd(1, img.dotSize/2-1)
  149. y += rnd(-img.dotSize/2, img.dotSize/2)
  150. if y <= 0 || y >= maxy {
  151. y = rnd(maxy/3, maxy-maxy/3)
  152. }
  153. img.drawCircle(img.primaryColor, x, y, r)
  154. }
  155. }
  156. func (img *Image) drawNumber(number []byte, x, y int) {
  157. skf := rand.Float64() * float64(rnd(-maxSkew, maxSkew))
  158. xs := float64(x)
  159. minr := img.dotSize / 2 // minumum radius
  160. maxr := img.dotSize/2 + img.dotSize/4 // maximum radius
  161. y += rnd(-minr, minr)
  162. for yy := 0; yy < fontHeight; yy++ {
  163. for xx := 0; xx < fontWidth; xx++ {
  164. if number[yy*fontWidth+xx] != blackChar {
  165. continue
  166. }
  167. // introduce random variations
  168. or := rnd(minr, maxr)
  169. ox := x + (xx * img.dotSize) + rnd(0, or/2)
  170. oy := y + (yy * img.dotSize) + rnd(0, or/2)
  171. img.drawCircle(img.primaryColor, ox, oy, or)
  172. }
  173. xs += skf
  174. x = int(xs)
  175. }
  176. }
  177. func setRandomBrightness(c *image.NRGBAColor, max uint8) {
  178. minc := min3(c.R, c.G, c.B)
  179. maxc := max3(c.R, c.G, c.B)
  180. if maxc > max {
  181. return
  182. }
  183. n := rand.Intn(int(max-maxc)) - int(minc)
  184. c.R = uint8(int(c.R) + n)
  185. c.G = uint8(int(c.G) + n)
  186. c.B = uint8(int(c.B) + n)
  187. }
  188. func min3(x, y, z uint8) (o uint8) {
  189. o = x
  190. if y < o {
  191. o = y
  192. }
  193. if z < o {
  194. o = z
  195. }
  196. return
  197. }
  198. func max3(x, y, z uint8) (o uint8) {
  199. o = x
  200. if y > o {
  201. o = y
  202. }
  203. if z > o {
  204. o = z
  205. }
  206. return
  207. }
  208. // rnd returns a random number in range [from, to].
  209. func rnd(from, to int) int {
  210. return rand.Intn(to+1-from) + from
  211. }