一個比較實用的php圖形驗證碼生成類,調用方法也很簡單的,有需要的朋友可以參考一下。 代碼如下 復制代碼
<?php
class ImageCode{
private $width;//驗證碼圖片寬度
private $height;//驗證碼圖片高度
private $codeNum;//驗證碼字符個數
private $checkCode;//驗證碼字符
private $image;//驗證碼畫布
function __construct($width=60,$height=20,$codeNum=4){
$this->width=$width;
$this->height=$height;
$this->codeNum=$codeNum;
$this->checkCode=$this->createCheckCode();
}
function getcreateImage(){
$this->getcreateImage();
$this->outputText();
$this->setDisturbColor();
$this->outputImage();
}
function getCheckCode(){
return $this->checkCode;
}
private function getCreateImage(){
$this->image=imagecreatetruecolor($this->width,$this->height);
$black=imagecolorallocate($this->image,255,255,255,0);
$border=imagecolorallocate($this->image,255,255,255,255);
imagefilledrectangle($this->image,0,0,$this->width-1,$this->height-1,$border);
}
private function createCheckCode(){
for($i=0;$i<$this->codeNum;$i){
$number=rand(0,2);
switch($number){
case 0:
$rand_number=rand(48,57);//數字
break;
case 1:
$rand_number=rand(65,90);//大寫字母
break;
case 2:
$rand_number=rand(97,122);
break;
}
$asc=sprintf("%c",$rand_number);
$asc_number=$asc_number.$asc;
}
return $asc_number;
}
private function setDisturbColor(){
for($i=0;$i<=100;$i++){
$color=imagecolorallocate($this->image,255,255,255);
imagesetpixel($this->image,rand(1,$this->width-2),rand(1,$this->height-2),$color);
}
}
private function outputImage(){
if(imagetypes()&IMG_GIF){
header("Content_type:image/gif");
imagegif($this->image);
}elseif(imagetypes()&IMG_JGP){
header("Content_type:image/jpeg");
imagejpeg($this->image,"",0.5);
}else{
die("PHP不支持圖像創建");
}
}
function __destruct(){
imagedestroy($this->image);
}
}
?>