自制验证码类

代码部分:

class makeyzm{

private $width = 100;
private $height = 50;
private $image;
private $font;
private $strings;
private $backcolor;
private $fontcolor;
private $linecolor;
private $pointcolor;

function __construct(){

$this->font = 'C:\WINDOWS\Fonts\MSYH.TTF';//引入微软雅黑字体

}
//设定画布
public function makebackground(){

$this->image = imagecreatetruecolor($this->width,$this->height);

}
//准备颜色
public function makecolor(){

//设定背景色
$this->backcolor = imagecolorallocate($this->image,248,248,255);
//设定字体颜色
$this->fontcolor = imagecolorallocate($this->image,0,255,255);
//设定干扰线颜色
$this->linecolor = imagecolorallocate($this->image,210,105,30);
//设定干扰点颜色
$this->pointcolor = imagecolorallocate($this->image,128,128,128);
}
//随机产生字体
public function makestrings(){

$arr = array();
$array = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');//验证码字符
$key = array_rand($array,4);
foreach($key as $k){
array_push($arr,$array[$k]);
}
$strings = implode("",$arr);//得到了随机的字符串,这里定义需要跟PHP文件交互
$this->strings = $strings;
imagestring($this->image,25,20,20,$this->strings,$this->fontcolor);
}
//制作干扰线、干扰点
public function makepointline(){

//三条线
for($i=0;$i<3;$i++){
$randwidthone = mt_rand(0,$this->width);
$randwidthtwo = mt_rand(0,$this->width);
$randheightone = mt_rand(0,$this->height);
$randheighttwo = mt_rand(0,$this->height);

imageline($this->image,$randwidthone,$randheightone,$randwidthtwo,$randheighttwo,$this->linecolor);
}
}
//填充颜色
public function fill(){

imagefill($this->image,0,0,$this->backcolor);

}
//输出在PHP页面并销毁原图
public function outimage(){

Header('Content-type: image/png');
imagepng($this->image);
imagedestroy($this->image);

}
//按顺序生成验证码图
public function makeimage(){

$this->makebackground();
$this->makecolor();
$this->fill();
$this->makestrings();
$this->makepointline();
$this->outimage();
}
//获取验证码
public function getstrings() {

return $this->strings;

}
}
$a = new makeyzm();
$a->makeimage();

思路解读:

分析:

验证码作为一个图片,本身有属性:宽、高、背景色、验证码字符串、验证码字体、干扰线点,方法有:制作画布、准备颜色、制作随机字符串、制作干扰线,输出图片,返回验证码数据。

类设计:

一、封装验证码属性

二、书写准备画布、颜色、字符串、干扰线的方法

三、输出方法和返回字符串数据方法

几个学习到的函数:

array_rand()随机抽取数组中的一个元素,返回它的键名。

array_push()将元素添加到一个数组中。

implode()将数组融合为一个字符串,可以添加连接符参数。

mt_rand()两个数中随机选取一个数

GD库函数:

imagecreatetruecolor()设定画布。

imagecolorallocate()给图像准备颜色,使用RGB参数。

imagefill()图片上色

imagestring()生成字符串

imageline()使用两个像素点,连接生成一条直线

imagepng()输出图像

imagedestroy()销毁原图

 最终效果图(不是很理想,下次再改进吧):

posted @ 2017-04-13 16:39  程昱仲德  阅读(230)  评论(0编辑  收藏  举报