验证码封装类

来源:互联网 发布:php json encode 在线 编辑:程序博客网 时间:2024/05/21 18:37

<?php
 class Captcha{
   private $width;  //验证码的宽度
   private $height;    //验证码的高度
   private $strNum;    //验证码字符的数量
   private $image;
   private $disTurbNum;

   public function __construct($width,$height,$strNum){
     $this->width = $width;
     $this->height = $height;
     $this->strNum = $strNum;
     $this-> disTurbNum = $this->width * $this->height/50; //像素密度
   }

   public function showImg(){
     //创建矩形框(背景颜色)
     $this->createBg();   
     //设置干扰元素(像素点、线条)
     $this->setDisturb();
     //输出文字到矩形框
     $str = $this->outPutStr();
     //输出\保存图像
     $this->outPutImg();
     return $str;
   }
   private function createBg(){
     //创建画布
     $this->image = imagecreatetruecolor($this->width,$this->height);
     //分配画笔颜色
     $bgColor =imagecolorallocate($this->image,mt_rand(50,255),mt_rand(50,255),mt_rand(50,255));
     //填充颜色
     imagefill($this->image,0,0,$bgColor);
     //给背景创建一个边框
     $borderColor = imagecolorallocate($this->image,0,0,0);
     imagerectangle($this->image,0,0,$this->width-1,$this->height-1,$border);
   }
   //设置干扰元素
   private function setDisturb(){
    //像素点
    for($i=0;$i<$this->disTurbNum;$i++){
     $pxColor = imagecolorallocate($this->image,mt_rand(100,225),mt_rand(100,225),mt_rand(100,225));
     imagesetpixel($this->image,mt_rand(1,$this->width-2),mt_rand(1,$this->height-2),$pxColor);
    }
    //线条
    for($j=0;$j<20;$j++){
     $lineColor = imagecolorallocate($this->image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200));
     imageline($this->image,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$lineColor);
    }
   }

   private function outPutStr(){
    //a-z   A-Z   0-9
    $lower_str = range('a','z');   //获得 从a-z之间的所有的单元
    $upper_str = range('A','Z');
    $num = range(0,9);
    //把这些数组合并
    $new_all = array_merge($lower_str,$upper_str,$num);
    //随机获得几个数组下标
    $keys = array_rand($new_all,$this->strNum);
    $str = '';
    //循环遍历下标,找到对应的元素
    foreach($keys as $value){
      $str .= $new_all[$value];
    }
    $strColor = imagecolorallocate($this->image,0,0,0);
    imagestring($this->image,5,20,10,$str,$strColor);
    //通常是保存到session
    $_SESSION['captcha'] = $str;
    return $_SESSION['captcha'];
   }

   private function outPutImg(){
    header('Content-Type:image/png');
    imagepng($this->image);
   }
   
   //销毁资源(析构方法----当类执行完毕会自动的调用这个方法)
   private function __destruct(){
     imagedestroy($this->image);
   }
 }

原创粉丝点击