这是正式在sf上面写文章,记录学习过程中的一些东西,这次主要是写一篇介绍如何使用php的gd库来生成验证码的文章,同时顺便学习一下markdown
验证码实现原理:使用php的GD库,生成一张带验证码的图片,并将验证码保存在Session中。php生成验证码的大致流程如下:
1.生成一张背景图片
2.将图片设置背景颜色
3.设置验证码的字体,字体颜色和样式
4.产生随机的验证码
5.把产生的每个字符调整角度和位置分别画到产生的图片上
6.加入噪点和干扰线
7.输出图片
8.释放图片所占内存
其中主要是第4步和第5步需要注意,下面是主要的代码
code.php
class code{
//字母和数字集合
private $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
private $length; //验证码长度
private $width; //图片宽度
private $height; //图片高度
private $font; // 字体
private $fontSize=16; //字体大小
private $img; //图像句柄
private $code;
function __construct($width,$height,$length){
$this->width = $width;
$this->height = $height;
$this->length = $length;
$this->img = imagecreate($this->width,$this->height);
$this->font = dirname(__FILE__).'\msyh.ttc'; //字体
$this->code = $this->getCode();
}
//创建背景图
function createBackground(){
$width = $this->width;
$height = $this->height;
//随机颜色
$r = Array(225, 255, 255, 223);
$g = Array(225, 236, 237, 255);
$b = Array(225, 236, 166, 125);
$key = mt_rand(0, 3);
$backgroundColor = imagecolorallocate($this->img, $r[$key], $g[$key], $b[$key]);
// //填充
imagefilledrectangle($this->img, 0, 0, $width , $height, $backgroundColor);
}
function createCode(){
$length = ($this->length)? $this->length:4; // 默认4位数
for($i = 0 ; $i < $length; $i++){
$code[$i] = $this->codeSet[mt_rand(0,strlen($this->codeSet-1))];
}
return $code;
}
//生成线条雪花
function createLine(){
//线条
for($i=0;$i<6;$i++){
$color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),
mt_rand(0,$this->width),mt_rand(0,$this->height),$color);
}
for($i = 0; $i < 20; $i++){
$color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),
'*',$color);
}
}
//生成文字
function createFont(){
//第N个字符的左边距
$codeNX = 0;
for ($i = 0; $ilength; $i++) {
$fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156));
$code[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet)-1)];
// print_r($code[$i]);die;
// print_r($this->font);die;
$codeNX += mt_rand($this->fontSize*1.2, $this->fontSize*1.6);
imagettftext($this->img, $this->fontSize, mt_rand(-40, 40),
$codeNX, $this->fontSize*1.2, $fontcolor, $this->font, $code[$i]);
}
}
function outPut(){
header('Content-type:image/png');
imagepng($this->img);
imagedestory($this->img);
}
function doimg(){
$this->createBackground();
$this->createCode();
$this->createLine();
$this->createFont();
$this->outPut();
}
public function getCode(){
$code = $this->createCode();
$cstring = '';
foreach($code as $str){
$cstring .= $str;
}
return strtolower($cstring);
}
}
?>