<?php
/*
* @version 1.0
* @author YSY
* @date 2013-07-07
* @name PHP验证码类
*
* 使用的方法:
* Create()-----------创建图片,并为图片上颜色,颜色随机生成
* imgColor()---------设置颜色,方便以后干扰素,文字颜色的需要
* imgDisturb()-------干扰素的生成
* imgCode()----------验证随机码的生成
* imgText()----------向图片写入文本
* outimg()-----------输出图片,提供三种格式输出,png,jpg,gif
*/
class Caotcha{
private $image; //验证码图片
private $img_width; //验证码图片宽
private $img_height; //验证码图片高
private $img_type; //验证码图片输出的类型,支持:png/jgg/gif
private $img_line_num; //干扰线的数量
private $img_pix_num ; //干扰点的数量
private $img_code_num; //文本的字数
function __construct($width,$height,$type,$line,$pix,$code){
$this->img_width = $width;
$this->img_height = $height;
$this->img_type = $type;
$this->img_line_num = $line;
$this->img_pix_num = $pix;
$this->img_code_num = $code;
$this->Create();
}
//*********创建图片*********
function Create(){
$this->image = imagecreate($this->img_width, $this->img_height);
imagecolorallocate($this->image, rand(155, 255), rand(155, 255), rand(155, 255));
return $this->image;
}
//*********创建颜色*********
function imgColor($red,$green,$blue){
$color = imagecolorallocate($this->image, $red, $green, $blue);
return $color;
}
//*********干扰素*********
function imgDisturb($color){
if ($this->img_line_num !=0){
for ($i=0;$i<$this->img_line_num;$i++){
imageline($this->image, rand(0, $this->img_width*0.2), rand(0, $this->img_height), rand($this->img_width*0.8, $this->img_width), rand(0, $this->img_height), $color);
}
}else {
return false;
}
if ($this->img_pix_num != 0){
for ($i=0;$i<$this->img_pix_num;$i++){
imagesetpixel($this->image, rand(0, $this->img_width), rand(0, $this->img_height), $color);
}
}else {
return false;
}
}
//*********验证码的生成*********
function imgCode(){
for ($o=0;$o<$this->img_code_num;$o++){
$rand=$rand.dechex(rand(1,15));
}
return $rand;
}
//*********向图像写入文本*********
function imgText($ttf,$color,$code){
imagettftext($this->image, rand(12, 18), rand(0, 5), rand(10, 20), rand(15, $this->img_height), $color, $ttf, $code);
}
//*********输出图片*********
function outimg(){
if ($this->img_type == 'png'){
header("content-type:image/png");
imagepng($this->image);
}elseif ($this->img_type == 'jpg'){
header("content-type:image/jpeg");
imagejpeg($this->image);
}elseif ($this->img_type == 'gif'){
header("content-type:image/gif");
imagegif($this->image);
}
}
}
?>
<?php
session_start();
include 'try.php';
$pic = new Caotcha(80, 30,'gif',4,120,4); //实例化Caotcha,设置图片的宽为80,高为30,输出图片类型gif,干扰线4,干扰点120,文本4
$color_l = $pic->imgColor(rand(170, 230), rand(170, 230), rand(170, 230));//设置两种随机颜色,color_l干扰素颜色,color_z文本的颜色
$color_z = $pic->imgColor(rand(100, 130), rand(100, 130), rand(100, 130));
$pic->imgDisturb($color_l); //调用的干扰素,并给它设置颜色
$code = $pic->imgCode(); //把生成的随机码调用出来,方便赋给session
$_SESSION[check_pic] = $code;
$pic->imgText('hyww.ttf', $color_z, $code); //设置一下输出文本的字体,还是输出字体的颜色
$pic -> outimg(); //输出图片,这里有三种图片格式,png,jpg,gif
?>