Capcha.php 2.5 KB

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