<?php
class CheckCode{
private $width;
private $height;
private $im;
private $text;
function __construct($width,$height){
$this->width=$width;
$this->height=$height;
}
function CreateCode(){
$this->ImageIni();//初始化图像
$this->CreateText();//生成验证码
$this->setDisturbColor();//设置干扰点
$this->outputImage();//向浏览器输出图片
}
//定义初始图像函数
private function ImageIni(){
$this->im = imagecreatetruecolor($this->width,$this->height);
$bgcolor = imagecolorallocate($this->im,rand(0,255),rand(0,255),rand(0,255));
$bordercolor = imagecolorallocate($this->im,0,0,0);
imagefill($this->im,$this->width-1,$this->height-1,$bgcolor);
imagerectangle($this->im,1,1,$this->width-1,$this->height-1,$bordercolor);
}
//定义产生随机字符函数
private function CreateText(){
$tcolor = imagecolorallocate($this->im,125,0,255);
for($i = 0;$i < 4; $i++){
$num_case = rand(0,2);//产生随机数0-2,根据数值的不同决定产生的是数字|小写|大写
switch($num_case){
case 0:$num = rand(48,57);break;//数字
case 1:$num = rand(65,90);break;//大写
default:$num = rand(97,122);//小写
}
$this->text[$i] = sprintf("%c",$num);//将随机产生的ASCII码转换为相应的字符
imagettftext($this->im,$this->height-5,rand(0,45),(($this->width-10)/4)*$i+5,$this->height-3,$tcolor,"STLITI.TTF",$this->text[$i]);//显示字符
}
}
//创建放置干扰点函数
private function setDisturbColor(){
$green = imagecolorallocate($this->im,0,255,0);
for($i=0;$i<100;$i++){
imagesetpixel($this->im,rand(1,$this->width-1),rand(1,$this->height-1),$green);
}
}
//创建图像输出函数
private function outputImage(){
if (imagetypes() & IMG_GIF){
header("Content-type:image/gif");//设置输出类型
imagegif($this->im);//输出图像
}
elseif(imagetypes() & IMG_PNG){
header("Content-type:image/png");//设置输出类型
imagepng($this->im);//输出图像
}
elseif(imagetypes() & IMG_JPG){
header("Content-type:image/jpeg");//设置输出类型
imagejpeg($this->im);//输出图像
}
elseif(imagetypes() & IMG_WBMP){
header("Content-type:image/wbmp");//设置输出类型
imagewbmp($this->im);//输出图像
}
else {
die("php不支持您的图像创建");
}
}
function getMessage(){
return implode($this->text);
}
}
//析构函数销毁图像,释放内存
function __destruct(){
imagedestroy($this->im);
}
?>