[PHP] 纯文本查看 复制代码
<?php
class Vcode{
// 定义变量
private $width, $height, $number, $code, $image;
// 构造函数
function __construct($width, $height, $number){
$this->width = $width;
$this->height = $height;
$this->number = $number;
$this->code = $this->create_code();
$this->image = imagecreate($this->width, $this->height);
}
// 输出图片
function out_img(){
// 创建颜色
$white = imagecolorallocate($this->image, 255, 255, 255);
$blank = imagecolorallocate($this->image, 0, 0, 0);
// 渲染背景、边框
imagefill($this->image, 0, 0, $white);
imagerectangle($this->image, 0, 0, $this->width-1, $this->height-1, $blank);
// 画图
$w = imagefontwidth(5); // 字体宽度
$h = imagefontheight(5); // 字体高度
$width = $this->width / $this->number; // 单字宽度
for ($i = 0; $i < $this->number; $i++){
// 每一个字符在各自四分之一个格子内随机
$x = rand($width * $i, $width + $width * $i - $w);
$y = rand(0, $this->height - $h);
// 颜色随机
$color = imagecolorallocate($this->image, rand(0, 200), rand(0, 200), rand(0, 200));
// 渲染字符
imagestring($this->image, 5, $x, $y, $this->code[$i], $color);
}
// 干扰元素点
for($i = 0; $i < 100; $i ++){
// 颜色随机
$color = imagecolorallocate($this->image, rand(0, 200), rand(0, 200), rand(0, 200));
// 位置在图像范围内
$x = rand(1, $this->width-2);
$y = rand(1, $this->height-2);
// 画一个像素点
imagesetpixel($this->image, $x, $y, $color);
// 增加10条干扰线条
if($i % 10 == 0){
// 椭圆长半径及短半径随机
$width = rand(20, 300);
$height = rand(20, 300);
// 随机画孤
imagearc($this->image, $x, $y, $width, $height, 55, 44, $color);
}
}
// 输出图像
return imagegif($this->image);
}
// 获取字符的验证码
function get_code(){
return $this->code;
}
// 生成验证码字符串
private function create_code(){
return "".rand(1000, pow(10, $this->number) - 1);
}
// 析构函数
function __destruct(){
imagedestroy($this->image);
}
}