创建验证码背景图像:
1)自定义长宽
2)背景颜色随着刷新自动切换
header('Content-type:image/jpeg');
$width=120;
$height=40;
$img=imagecreatetruecolor($width,$height);
$colorBg=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
imagefill($img,0,0,$colorBg);
imagejpeg($img);
画验证码修饰图:
1)画一个矩形
$colorBorder=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
imagerectangle($img,0,0,$width-1,$height-1,$colorBorder);
2)画大量像素点
$colorPixel=imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200));
for ($i=0;$i<100;$i++){
imagesetpixel($img,rand(0,$width-1),rand(0,$height-1),$colorPixel);
}
3)画多条线
$colorLine=imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200));
for ($i=0;$i<3;$i++){
imageline($img,rand(0,($width-1)/2),rand(0,$height),rand($width/2,$width),rand(0,$height),$colorLine);
}
4)写入字符串
1. 普通字体
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagestring($img,5,0,0,'abcd',$colorString);
2. 指定字体
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagettftext($img,14,0,0,39,$colorString,'font/Elements.ttf','abcd');
3)多样验证码
$element=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z');
$string='';
for ($i=0;$i<5;$i++){
$string.=$element[rand(0,count($element)-1)];
}
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagettftext($img,14,rand(-5,5),rand(5,15),rand(30,35),$colorString,'font/Elements.ttf',$string);
代码汇总:
header('Content-type:image/jpeg');
$width=120;
$height=40;
$element=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z');
$string='';
for ($i=0;$i<5;$i++){
$string.=$element[rand(0,count($element)-1)];
}
$img=imagecreatetruecolor($width,$height);
$colorBg=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
imagefill($img,0,0,$colorBg);
$colorBorder=imagecolorallocate($img,rand(200,255),rand(200,255),rand(200,255));
imagerectangle($img,0,0,$width-1,$height-1,$colorBorder);
$colorPixel=imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200));
for ($i=0;$i<100;$i++){
imagesetpixel($img,rand(0,$width-1),rand(0,$height-1),$colorPixel);
}
$colorLine=imagecolorallocate($img,rand(100,200),rand(100,200),rand(100,200));
for ($i=0;$i<3;$i++){
imageline($img,rand(0,($width-1)/2),rand(0,$height),rand($width/2,$width),rand(0,$height),$colorLine);
}
$colorString=imagecolorallocate($img,rand(10,100),rand(10,100),rand(10,100));
imagettftext($img,14,rand(-5,5),rand(5,15),rand(30,35),$colorString,'font/Elements.ttf',$string);
imagejpeg($img);
imagedestroy($img);