- 使用前查看一下php.ini中extension=gd2前的分号去掉了没,默认是去掉的。修改php.ini后需要重启Apache服务器修改才能生效。
- 直接看代码吧
header("Content-type:text/html;charset=UTF-8");
$image = imagecreatetruecolor(120,40);
$font = 'C:/Windows/Fonts/simhei.ttf';
$bg = imagecolorallocate($image,255,255,0);
// 填充
imagefill($image,0,0,$bg);
// 绘制干扰线
for($i=0;$i<5;$i++) {
$lineColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imageline($image,rand(0,120),rand(0,40),rand(0,100),rand(0,20),$lineColor);
}
// 绘制干扰点
for($i=0; $i<100; $i++) {
$pointColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
imagesetpixel($image,rand(1,119),rand(1,39),$pointColor);
}
// 添加验证码
for($i=0; $i<4; $i++) {
$textColor = imagecolorallocate($image, rand(50,200), rand(50,200), rand(50,200));
$m = rand(0,9);
imagettftext($image,20,rand(30,-30),($i*20+10),rand(20,30),$textColor,$font,$m);
}
header("Content-type:image/jpeg");
imagejpeg($image);
imagedestroy($image);
效果如图:
如果上述代码中有不明白的函数请去http://php.net/manual/zh/上搜索。