yzSes.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. class ValidateCode {
  3. private $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';//随机因子
  4. private $code;//验证码
  5. private $codelen = 4;//验证码长度
  6. private $width = 120;//宽度
  7. private $height = 38;//高度
  8. private $img;//图形资源句柄
  9. private $font;//指定的字体
  10. private $fontsize = 20;//指定字体大小
  11. private $fontcolor;//指定字体颜色
  12. //构造方法初始化
  13. public function __construct() {
  14. $this->font = dirname(__FILE__).'/font/Elephant.ttf';//注意字体路径要写对,否则显示不了图片
  15. }
  16. //生成随机码
  17. private function createCode() {
  18. $_len = strlen($this->charset)-1;
  19. for ($i=0;$i<$this->codelen;$i++) {
  20. $this->code .= $this->charset[mt_rand(0,$_len)];
  21. }
  22. }
  23. //生成背景
  24. private function createBg() {
  25. $this->img = imagecreatetruecolor($this->width, $this->height);
  26. $color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255));
  27. imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color);
  28. }
  29. //生成文字
  30. private function createFont() {
  31. $_x = $this->width / $this->codelen;
  32. for ($i=0;$i<$this->codelen;$i++) {
  33. $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
  34. imagettftext($this->img,$this->fontsize,mt_rand(-30,30),$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]);
  35. }
  36. }
  37. //生成线条、雪花
  38. private function createLine() {
  39. //线条
  40. for ($i=0;$i<6;$i++) {
  41. $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
  42. imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
  43. }
  44. //雪花
  45. for ($i=0;$i<100;$i++) {
  46. $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
  47. imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color);
  48. }
  49. }
  50. //输出
  51. private function outPut() {
  52. header('Content-type:image/png');
  53. imagepng($this->img);
  54. imagedestroy($this->img);
  55. }
  56. //对外生成
  57. public function doimg() {
  58. $this->createBg();
  59. $this->createCode();
  60. $this->createLine();
  61. $this->createFont();
  62. $this->outPut();
  63. }
  64. //获取验证码
  65. public function getCode() {
  66. return strtolower($this->code);
  67. }
  68. }
  69. ?>