驗證碼封裝類

<?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);
   }
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章