您的位置:首页 > 编程语言 > PHP开发

php验证码的类

2016-06-27 10:22 561 查看
<?php
// 1. 创建画布
// 2. 分配颜色
// 3. 填充背景
// 4. 开始绘画
// 5. header输出
// 6. 销毁资源

//声明类
//  类名:Vcode
//  参数:  宽度 高度
//  方法: createVcode

class Vcode{
//成员属性
private $width;
private $height;
private $allStr = "";
private $res = null;//当前图片的资源

//构造方法
public function __construct($width,$height){
$this->width = $width;
$this->height = $height;
}

//成员方法
public function createVcode(){
// 1创建画布
$this->createRes();
//2.分配颜色 填充画布
$this->fenpei();
//3.干扰元素
$this->disturb();
//4.获取字符
$this->getCodes();
//5.写入字符
$this->writeCode();
//6.输出图片
$this->outPut();
//7.销毁资源
imagedestroy($this->res);
}

private function outPut(){
header('content-type:image/png');
imagepng($this->res);
}

//写入
// 说明  abcd
// imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
private function writeCode(){
for($i=0;$i<4;$i++){
$size = 14;//字体大小
$angle = rand(-10, 10);//0 0  1 25 2 50 3 75
$p = $this->width/4-5;//平均值
$x = $i*$p+20;
$y = rand($size+10,$this->height);
$color = imagecolorallocate($this->res, rand(0,125),rand(0,125),rand(0,125));
$fontfile = "msyh.ttf";
$text = $this->allStr{$i};
imagettftext($this->res, $size, $angle, $x, $y, $color, $fontfile, $text);
}
}

//获取字符方法  2345  jklm
private function getCodes(){
//字符库
$str = "23456789qwertyuipasdfghjkzxcbnm";//20   19
$len = strlen($str);//20
$allStr = "";
for($i=0;$i<4;$i++){
//随机下标
$index = rand(0, $len-1);
//获取最忌字符
$ch = $str{$index};
$allStr .= $ch;
}
//存入成员属性中
$this->allStr = $allStr;
//写入session
session_start();
$_SESSION['vcode'] = $allStr;
}

private function disturb(){
//创建干扰点  imagesetpixel  20
// bool imagesetpixel ( resource $image , int $x , int $y , int $color )
for($i = 0;$i<20;$i++){
$x = rand(0, $this->width);
$y = rand(0, $this->height);
$r = rand(0,255);
$g = rand(0,255);
$b = rand(0,255);
$color = imagecolorallocate($this->res, $r, $g, $b);
//画点
imagesetpixel($this->res, $x, $y, $color);
}

//创建干扰线
// bool imageline ( resource $image , int $x1 , int $y1 , int $x2 , int $y2 , int $color )
for($i=0;$i<10;$i++){
$x1 = rand(0, $this->width);
$y1 = rand(0, $this->height);
$x2 = rand(0, $this->width);
$y2 = rand(0, $this->height);
$r = rand(0, 255);
$g = rand(0, 255);
$b = rand(0, 255);
$color = imagecolorallocate($this->res, $r, $g, $b);
//开始画线
imageline($this->res, $x1, $y1, $x2, $y2, $color);
}
}

//填充
private function fenpei(){
//imagecolorallocate
$color = imagecolorallocate($this->res, rand(125,255), rand(125,255), rand(125,255));
//imagefill
imagefill($this->res, 0,0, $color);
}

private function createRes(){
//创建画布
$this->res = imagecreatetruecolor($this->width, $this->height);
}
}

$vcode = new Vcode(100,50);
$vcode->createVcode();

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息