目标:用 php-gd 库的 api 实现验证码功能
//创建画布
$width=180;
$height=50;
$image=imagecreatetruecolor($width,$height);
//创建颜色
$white=imagecolorallocate($image,255,255,255);
//绘制矩形并填充
imagefilledrectangle($image,0,0,$width,$height,$white);
//创建一个画笔颜色
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
$str=join("",array_merge(range(0,9),range('a','z'),range('A','Z')));
//一个一个的绘制验证码,4个字符字体大小不同,角度不同,颜色不同
$length=4;
for($i=0;$i
$size=mt_rand(20,28);//字体大小
$textHeight=imagefontheight($size);//字体宽度
$textWidth=imagefontwidth($size);//字体高度
$angle=mt_rand(-15,15);//角度
$x=20+($width/$length)*$i;//x坐标
$y=mt_rand($height-$textHeight,$height);//y坐标
$fontfile='font/ANTQUABI.TTF';//字体库文件
$text=str_shuffle($str){0};//字符串
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagettftext($image,$size,$angle,$x,$y,$randColor,$fontfile,$text);
}
//添加50个点 干扰元素
for($i=0;$i<50;$i++){
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),$randColor);
}
//添加线段干扰元素
for($i=0;$i<3;$i++){
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),$randColor);
}
//绘制圆弧
for($i=0;$i<2;$i++){
$randColor=imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
imagearc($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width/2),mt_rand(0,$height/2),0,360,$randColor);
}
//告诉浏览器以图像的形式显示
header("content-type:image/png");
//输出图像
imagepng($image);
//销毁资源
imagedestroy($image);