<?php
/*
* Created on 2013-7-19
*
* 验证码类
* 通过类的对象可以动态获取验证码图片和验证正码字符串。
*/
class ValidationCode{
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 showImage(){
$this->getCreateImage();//初始化画布
$this->outputText();//向图像写入随机字符
$this->setDisturbColor();//向图像添加一些干扰像素
$this->outputImage();//生成相应格式的图像,并输出
}
function getCheckCode(){
return $this->checkCode;
}
/**
* 创建图像
*/
private function getCreateImage(){
$this->image=imagecreate($this->width,$this->height);
$back=imagecolorallocate($this->image,255,255,255);
$border=imagecolorallocate($this->image,0,0,0);
imagerectangle($this->image,0,0,$this->width,$this->height-1,$border);
}
/**
* 生成验证码
*/
private function createCheckCode(){
for($i=0;$i<$this->codeNum;$i++){
$number=mt_rand(0,2);
switch($number){
case 0:$rand_number=mt_rand(48,57);break;//数字
case 1:$rand_number=mt_rand(65,90);break;//大写字母
case 2:$rand_number=mt_rand(97,122);break;//小写字母
}
$ascii=sprintf("%c",$rand_number);
$ascii_number=$ascii_number.$ascii;
}
return $ascii_number;
}
/**
* 设置干扰像素
*/
private function setDisturbColor(){
for($i=0;$i<100;$i++){
$color=imagecolorallocate($this->image,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($this->image,rand(1,$this->width-2),rand(1,$this->height-2),$color);
}
}
/**
* 将验证码写在画布上
*/
private function outputText(){
for($i=0;$i<$this->codeNum;$i++){
$bg_color=imagecolorallocate($this->image,rand(0,255),rand(0,128),rand(0,255));
$x=floor($this->width/$this->codeNum)*$i+3;//x轴位置的算法
$y=rand(0,$this->height-15);
imagechar($this->image,5,$x,$y,$this->checkCode[$i],$bg_color);
}
}
/**
* 按照GD库生成的格式输出图像
*/
private function outputImage(){
if(imagetypes()&IMG_GIF){
header("Content-type:image/gif");
imagegif($this->image);
}else if(imagetypes()&IMG_JPG){
header("Content-type:image/jpg");
imagejpeg($this->image);
}else if(imagetypes()&IMG_PNG){
header("Content-type:image/png");
imagepng($this->image);
}else if(imagetypes()&IMG_WBMP){
header("Content-type:image/vnd.wap.wbmp");
imagewbmp($this->image);
}else{
die("php不支持图像创建!");
}
}
/**
* 析构函数,释放图像所占内存
*/
function __destruct(){
imagedestroy($this->image);
}
}
//验证
$image=new ValidationCode(60,20,4);
$image->showImage();
?>