以前生成验证码的文件掉了,又只有重新写一个。有以下优点:
1、文字大小可以设置,我随便复制了一个windows的arial.ttf字体
2、随机字符没有大写,因为有些字母大小写分不清楚;
3、去掉了数字0和1,以及字母的o和l,同理它们容易混淆,用户体验不好。
header("Content-type:image/png");
$num = 4; //字符个数
$width = 70; // 图像宽度
$height = 40; // 图像高度
$size = 16; // 文字大小
$str = "abcdefghijkmnpqrstuvwxyz23456789"; //随机字符
$code = "";
for ($i = 0; $i < $num; $i++) {
$code .= substr($str, rand(0, strlen($str) - 1), 1);
}
$_SESSION["validate_code"] = $code; //改成你自己的session键
//创建图片
$im = imagecreate($width, $height);
//填充背景
$bg_color = imagecolorallocate($im, rand(200,255), rand(200,255), rand(200,255));
imagefill($im, 0, 0, $bg_color);
//干扰点
for($m = 0; $m <= 100; $m++){
$point_color=imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
imagesetpixel($im, rand(0, $width - 1), rand(0, $height - 1), $point_color);
}
//干扰线
for ($i = 0;$i <= 4;$i++){
$line_color = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
imageline($im, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $line_color);
}
$rand_x = rand(1, 6);
for ($i = 0; $i < $num; $i++) {
$font_color = imagecolorallocate($im, rand(0,120), rand(0,120), rand(0,120));
// imagestring($im, 5, $strx, $strpos, substr($code, $i, 1), $font_color); //缺点是字体大小不能控制
// imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $font_file , string $text )
@imagettftext($im, $size, rand(-15, 15), $rand_x, 20 + rand(0,8), $font_color, '/font/arial.ttf', substr($code, $i, 1)); // 换成你自己的字体文件物理路径
$rand_x += 16 + rand(0, 2);
}
imagepng($im);
imagedestroy($im);