PHP提供了一系列函数来实现在网站编程中对图像进行编辑。PHP的图像处理函数都封装在一个函数库中,这就是GD库。GD库用于处理图像,它是一个开放源码的动态创建图像的函数库,可以创建和操作多种不同格式的图像文件,并可以直接以图像流将图像输出到浏览器。
GD库在很多需要动态生成图像、自动批量处理图像等方面,能给PHP网站开发者带来巨大帮助,如:将用户上传到服务器的相片生成缩略图以供预览;为防止恶意攻击等而使用的验证码图片;给自己的图片加入版权信息等水印。以及数据统计中饼状图、柱形图和折线图等。
一、创建画布及常用颜色
1.1 创建画布
$num = 4;
$imgW = 102; // 画布宽度
$imgH =40; // 画布高度
$img = imagecreatetruecolor($imgW,$imgH); // 创建画布
1.2 常用颜色
$white = imagecolorallocate($img, 255, 255, 255); // 白色
$gray = imagecolorallocate($img, 228, 228, 228); // 灰色
// 我们将一系列颜色存入$color[]数组里
$color[] = imagecolorallocate($img, 255, 0, 0 ); // $red
$color[] = imagecolorallocate($img, 190, 8, 10 ); // $red--
$color[] = imagecolorallocate($img, 243, 97, 97 ); // $red--
$color[] = imagecolorallocate($img, 94, 153, 11 ); // $green
$color[] = imagecolorallocate($img, 124, 145, 0 ); // $grass
$color[] = imagecolorallocate($img, 107, 193, 70 ); // $gree--
$color[] = imagecolorallocate($img, 83, 104, 189); // blue
二、填充画布及创建边框
imagefill($img, 0, 0, $white); // 用$white填充画布
imagerectangle($img, 0, 0, $imgW-1, $imgH-1, $gray); // 创建一个$gray边框
三、添加验证码内容
3.1 引入字体
// 这里我们将字体文件存入一个数组,方便以后随机调用
$fonts[] = "msyh.ttf";
$fonts[] = "ninefeetunder.ttf";
$fonts[] = "bubblesoap.ttf";
$fonts[] = "DPStick.ttf";
3.2 验证码内容
$verifyText = getVerifyCode($num,2);
/**
* 生成验证码内容函数
* @Parameter $num,默认为4,即创建4个字符的验证码
* @Parameter $type,默认为0,即创建验证码类型为纯数字
*/
function getVerifyCode($num=4,$type=0){
$showStr = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$opNum = array(9,35,strlen($showStr)-1);
$str = "";
for ($i=0; $i
$str .= $showStr[rand(0,$opNum[$type])];
}
return $str;
}
3.3 生成验证码内容
$textColor = $color[rand(0,count($color)-1)]; // 随机显示文字字体颜色
$fontsType = $fonts[rand(0,count($fonts)-1)]; // 随机显示文字字体类型
for ($i=0; $i
imagettftext(
$img, //
28, // 字体大小
rand(-20,20), // 文字旋转角度
4+($i*23), // 依次将文字内容遍历显示,x轴
rand(32,34), // 文字内容y轴显示位置
$textColor, // 文字字体颜色
$fontsType, // 文字字体类型
$verifyText[$i] // 文字内容
);
}
3.4 随机添加干扰点
for($i=0;$i<150;$i++){
$dot = imagecolorallocate($img,rand(0,255),rand(0,255),rand(0,255)); //随机一个颜色
imagesetpixel($img,rand(1,$imgW-2),rand(1,$imgH-2),$dot);
}
3.5 随机添加干扰线
$linkColor = $color[rand(0,count($color)-1)]; // 随机获取颜色
for($i=0;$i<2;$i++){ // 随机生成两条干扰线
imageline($img,rand(0,$imgW),rand(0,$imgH),rand(0,$imgW),rand(0,$imgH),$linkColor);
}
四、输出验证码
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
五、效果展示
六、帮助文档
6.1 imagecreatetruecolor() -- 新建一个真彩色图像
6.2 imagecolorallocate() -- 为一幅图像分配颜色
6.3 imagefill() -- 区域填充
6.4 imagerectangle() -- 画一个矩形
6.5 imagettftext() -- 用 TrueType 字体向图像写入文本
6.6 imagesetpixel() -- 画一个单一像素
6.7 imageline() -- 画一条线段
6.8 imagepng()
6.9 imagedestroy() -- 销毁一图像