Captcha.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. /**
  3. * @class Captcha
  4. * @brief 验证码生成类库
  5. */
  6. class Captcha
  7. {
  8. /** Width of the image */
  9. public $width = 200;
  10. /** Height of the image */
  11. public $height = 70;
  12. /**
  13. * Path for resource files (fonts, words, etc.)
  14. * "resources" by default. For security reasons, is better move this
  15. * directory to another location outise the web server
  16. */
  17. /** Min word length (for non-dictionary random text generation) */
  18. public $minWordLength = 4;
  19. /**
  20. * Max word length (for non-dictionary random text generation)
  21. * Used for dictionary words indicating the word-length
  22. * for font-size modification purposes
  23. */
  24. public $maxWordLength = 5;
  25. /** Sessionname to store the original text */
  26. public $session_var = 'captcha';
  27. /** Background color in RGB-array */
  28. public $backgroundColor = array(255, 255, 255);
  29. /** Foreground colors in RGB-array */
  30. public $colors = array(
  31. array(27,78,181), // blue
  32. array(22,163,35), // green
  33. array(214,36,7), // red
  34. );
  35. /** Shadow color in RGB-array or null */
  36. public $shadowColor = null; //array(0, 0, 0);
  37. public $fontSize = 25;
  38. /**
  39. * Font configuration
  40. * - font: TTF file
  41. * - spacing: relative pixel space between character
  42. * - minSize: min font size
  43. * - maxSize: max font size
  44. */
  45. public $fonts = array(
  46. 'Time' => array('spacing' => 2, 'minSize' => 22, 'maxSize' => 24, 'font' => 'font.ttf'),
  47. );
  48. /** Wave configuracion in X and Y axes */
  49. public $Yperiod = 12;
  50. public $Yamplitude = 14;
  51. public $Xperiod = 11;
  52. public $Xamplitude = 5;
  53. /** letter rotation clockwise */
  54. public $maxRotation = 8;
  55. /**
  56. * Internal image size factor (for better image quality)
  57. * 1: low, 2: medium, 3: high
  58. */
  59. public $scale = 3;
  60. /**
  61. * Blur effect for better image quality (but slower image processing).
  62. * Better image results with scale=3
  63. */
  64. public $blur = false;
  65. /** Debug? */
  66. public $debug = false;
  67. /** Image format: jpeg or png */
  68. public $imageFormat = 'jpeg';
  69. /** GD image */
  70. public $im;
  71. public function __construct($config = array()) {
  72. }
  73. public function CreateImage(&$text='') {
  74. $ini = microtime(true);
  75. /** Initialization */
  76. $this->ImageAllocate();
  77. /** Text insertion */
  78. $text = $this->GetCaptchaText();
  79. $fontcfg = $this->fonts[array_rand($this->fonts)];
  80. $this->WriteText($text, $fontcfg);
  81. /** Transformations */
  82. $this->WaveImage();
  83. if ($this->blur && function_exists('imagefilter'))
  84. {
  85. imagefilter($this->im, IMG_FILTER_GAUSSIAN_BLUR);
  86. }
  87. $this->ReduceImage();
  88. if ($this->debug)
  89. {
  90. imagestring($this->im, 1, 1, $this->height-8,
  91. "$text {$fontcfg['font']} ".round((microtime(true)-$ini)*1000)."ms",
  92. $this->GdFgColor
  93. );
  94. }
  95. /** Output */
  96. $this->WriteImage();
  97. $this->Cleanup();
  98. }
  99. /**
  100. * Creates the image resources
  101. */
  102. protected function ImageAllocate()
  103. {
  104. // Cleanup
  105. if (!empty($this->im))
  106. {
  107. imagedestroy($this->im);
  108. }
  109. $this->im = imagecreatetruecolor($this->width*$this->scale, $this->height*$this->scale);
  110. // Background color
  111. $this->GdBgColor = imagecolorallocate($this->im,
  112. $this->backgroundColor[0],
  113. $this->backgroundColor[1],
  114. $this->backgroundColor[2]
  115. );
  116. imagefilledrectangle($this->im, 0, 0, $this->width*$this->scale, $this->height*$this->scale, $this->GdBgColor);
  117. // Foreground color
  118. $color = $this->colors[mt_rand(0, sizeof($this->colors)-1)];
  119. $this->GdFgColor = imagecolorallocate($this->im, $color[0], $color[1], $color[2]);
  120. // Shadow color
  121. if (!empty($this->shadowColor) && is_array($this->shadowColor) && sizeof($this->shadowColor) >= 3)
  122. {
  123. $this->GdShadowColor = imagecolorallocate($this->im,
  124. $this->shadowColor[0],
  125. $this->shadowColor[1],
  126. $this->shadowColor[2]
  127. );
  128. }
  129. }
  130. /**
  131. * Text generation
  132. *
  133. * @return string Text
  134. */
  135. protected function GetCaptchaText()
  136. {
  137. $text = $this->GetRandomCaptchaText();
  138. return $text;
  139. }
  140. /**
  141. * Random text generation
  142. * @return string Text
  143. */
  144. protected function GetRandomCaptchaText($length = null)
  145. {
  146. if (empty($length))
  147. {
  148. $length = rand($this->minWordLength, $this->maxWordLength);
  149. }
  150. $words = "abcdefghijlmnopqrstvwyz";
  151. $vocals = "aeiou";
  152. $text = "";
  153. $vocal = rand(0, 1);
  154. for ($i=0; $i<$length; $i++)
  155. {
  156. if ($vocal)
  157. {
  158. $text .= substr($vocals, mt_rand(0, 4), 1);
  159. }
  160. else
  161. {
  162. $text .= substr($words, mt_rand(0, 22), 1);
  163. }
  164. $vocal = !$vocal;
  165. }
  166. return $text;
  167. }
  168. /**
  169. * Text insertion
  170. */
  171. protected function WriteText($text, $fontcfg = array())
  172. {
  173. if (empty($fontcfg))
  174. {
  175. // Select the font configuration
  176. $fontcfg = $this->fonts[array_rand($this->fonts)];
  177. }
  178. // Full path of font file
  179. $fontfile = dirname(__FILE__).DIRECTORY_SEPARATOR.$fontcfg['font'];
  180. /** Increase font-size for shortest words: 9% for each glyp missing */
  181. $lettersMissing = $this->maxWordLength-strlen($text);
  182. $fontSizefactor = 1+($lettersMissing*0.09);
  183. //$fontspace = $this->width/strlen($text)-2;
  184. //$minSize = $fontspace;
  185. //$maxSize= $fontspace;
  186. // Text generation (char by char)
  187. $x = 20*$this->scale;
  188. $y = round(($this->height*27/40)*$this->scale);
  189. $length = strlen($text);
  190. for ($i=0; $i<$length; $i++)
  191. {
  192. $degree = rand($this->maxRotation*-1, $this->maxRotation);
  193. $fontsize = rand($this->fontSize+1, $this->fontSize-1)*$this->scale*$fontSizefactor;
  194. //$fontsize = $maxSize*$this->scale*$fontSizefactor;
  195. $letter = substr($text, $i, 1);
  196. if ($this->shadowColor)
  197. {
  198. $coords = imagettftext($this->im, $fontsize, $degree,
  199. $x+$this->scale, $y+$this->scale,
  200. $this->GdShadowColor, $fontfile, $letter);
  201. }
  202. $coords = imagettftext($this->im, $fontsize, $degree,
  203. $x, $y,
  204. $this->GdFgColor, $fontfile, $letter);
  205. $x += ($coords[2]-$x) + ($fontcfg['spacing']*$this->scale);
  206. }
  207. }
  208. /**
  209. * Wave filter
  210. */
  211. protected function WaveImage()
  212. {
  213. // X-axis wave generation
  214. $xp = $this->scale*$this->Xperiod*rand(1,3);
  215. $k = rand(0, 100);
  216. for ($i = 0; $i < ($this->width*$this->scale); $i++)
  217. {
  218. imagecopy($this->im, $this->im,
  219. $i-1, sin($k+$i/$xp) * ($this->scale*$this->Xamplitude),
  220. $i, 0, 1, $this->height*$this->scale);
  221. }
  222. // Y-axis wave generation
  223. $k = rand(0, 100);
  224. $yp = $this->scale*$this->Yperiod*rand(1,2);
  225. for ($i = 0; $i < ($this->height*$this->scale); $i++)
  226. {
  227. imagecopy($this->im, $this->im,
  228. sin($k+$i/$yp) * ($this->scale*$this->Yamplitude), $i-1,
  229. 0, $i, $this->width*$this->scale, 1);
  230. }
  231. }
  232. /**
  233. * Reduce the image to the final size
  234. */
  235. protected function ReduceImage()
  236. {
  237. $imResampled = imagecreatetruecolor($this->width, $this->height);
  238. imagecopyresampled($imResampled, $this->im,
  239. 0, 0, 0, 0,
  240. $this->width, $this->height,
  241. $this->width*$this->scale, $this->height*$this->scale
  242. );
  243. imagedestroy($this->im);
  244. $this->im = $imResampled;
  245. }
  246. /**
  247. * File generation
  248. */
  249. protected function WriteImage()
  250. {
  251. if ($this->imageFormat == 'png' && function_exists('imagepng'))
  252. {
  253. header("Content-type: image/png");
  254. imagepng($this->im);
  255. }
  256. else
  257. {
  258. header("Content-type: image/jpeg");
  259. imagejpeg($this->im, null, 90);
  260. }
  261. }
  262. /**
  263. * Cleanup
  264. */
  265. protected function Cleanup()
  266. {
  267. imagedestroy($this->im);
  268. }
  269. }
  270. ?>