1、创建画布
$image = imagecreatecolor($width, $height);
2、定义要用到的颜色
$white = imagecolorallocate($image, 255, 255, 255);
$blank = iamgecolorallocate($image, 0, 0, 0);
3、填充画布
imagesfilledrectangle($image, 1, 1, $width-2,$height-2, $white);
4、生成验证码文本内容
$str = join("", array_merge(range("a","z"), range("A","Z"), range(0,9))); //拼接字符串
$str = str_shuffle($str); //打乱字符串
$str = substr($str, 0, $length); //截取字符串
5、将验证码字符串放到session中,方便比对。
$SESSION['vertify'] = $str;
6、产生验证码
//此处每次循环一个,保证每一个字样式都不同
for($i=0;$i<$length,$i++){
$size = mt_rand(14, 18); //字体大小
$angle = mt_rand(-15, 15); //角度
$x = 5+$i*$size; //横坐标
$y = mt_rand(20, 26); //纵坐标
$fontfile = "../fonts/".$fontfiles[mt_rand(0,count($fontfiles)-1)]; //对应的字体拷到fonts目录下,并创建一个相应数组,此处将随机选取字体。
$text = substr($tr, $i, 1); 每次取一位
imagettftext($image, $size, $angle, $x, $y ,$color, $fontfile, $text);
}
7、显示验证码
header(context-type="text/gif"); //定义图片类型
imagegif($image); //输出图片
imagedestroy($image); //销毁图片,释放内存