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

PHP的GD库学习2:一个简单的验证码图片

2009-10-06 23:36 519 查看
使用两个函数增加验证码图片复杂程度,加干扰线和噪点。

1.imageline 与 imagesetpixel 函数

imageline 画线函数

imageline ( resource image, int x1, int y1, int x2, int y2, int color )

imagesetpixel 画点函数

imagesetpixel ( resource image, int x, int y, int color )

2.imagettftext函数调用字体写入文字

imagettftext 带字体的写入函数

imagettftext ( resource image, float size, float angle, int x, int y, int color, string fontfile, string text )

一个做好的测试程序

<?php
//生成四位随机数
for ($i = 0; $i < 4; $i++) {
$rand .= dechex(rand(1, 15));
}
//生成随机字体
$randfont = rand(1, 6);
//生成随机x坐标
$randx = rand(2, 70);
//生成随机y坐标
$randy = rand(2, 15);
//创建100x30大小的图片
$im = imagecreatetruecolor(100, 30);
//设置图片背景颜色为RGB 0,0,0
$bg = imagecolorallocate($im, 0, 0, 0);
//获得RGB 255,255,255 的颜色编码
$color = imagecolorallocate($im, 255, 255, 255);
//添加干扰线
for ($i = 0; $i < 5; $i++) {
$x1 = rand(0, 100);
$y1 = 0;
$x2 = rand(0, 100);
$y2 = 30;
$linecolor = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
imageline($im,$x1,$y1,$x2,$y2,$linecolor);
}
//添加噪点
for ($i = 0; $i < 200; $i++) {
$x = rand(0, 100);
$y = rand(0, 30);
$pixcolor = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255));
imagesetpixel($im, $x, $y, $pixcolor);
}
//更改文字编码
$string = iconv("gbk", "UTF-8", "新年好");
//在图片中写入文字
imagettftext($im, 12, -2, 2, 15, $color, 'simyou.ttf', $string);
//在图片中写入随机数
//imagestring($im, $randfont, $randx, $randy, $rand, $color);
//设置内容格式为images/jpeg
header("Content-Type: image/jpeg");
//输出jpeg图片
imagejpeg($im);
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: