PHP生成一个随机4个字符的图像验证码
源代码获取:
https://github.com/akh5/PHP/blob/master/identify_code.php

生成图像验证码大致需要4个步骤
生成随机4位字符串
//将数字字母合并到一个数组
$arr = array_merge(range('A','Z'),range('a','z'),range('0','9'));
shuffle($arr); //打乱数组
//选出数组的前四位作为验证码
for($i=0;$i<4;$i++)
{
$str.=$arr[$i];
}
- 通过array_merge函数将范围为A~Z,a~z,0~9的数组合为一个数组
- shuffle打乱数组
- 最后选取数组的前2位作为验证码,字符串拼接
创建一个空画布,并分配颜色
//声明浏览器格式
header("Content-Type:image/png");
//创建画布
$width = 150;
$height = 50;
$img = imagecreatetruecolor($width,$height);
//设置随机颜色颜色
$color1 = imagecolorallocate($img,mt_rand(0,100),mt_rand(50,150),mt_rand(100,200));
$color2 = imagecolorallocate($img,mt_rand(150,255),mt_rand(150,255),mt_rand(150,255));
- 声明浏览器格式
- imagecreatetruecolor创建画布,设定宽高
- imagecolorallocate设定随机颜色,color1深色作为背景,color2浅色作为字体颜色
绘制矩形,并往图像上写入TTF字体字符串
//ttf字体绝对路径
$fontpath = "E:/wamp64/www/day4/font/msyh.ttc";
//在画布中绘制矩形
imagefilledrectangle($img,0,0,$width,$height,$color1);
//添加ttf字体,生成随机的验证码
imagettftext($img,28,0,20,40,$color2,$fontpath,$str);
- 设定TTF字体的绝对路径
- imagefilledrectangle绘制一个矩形填充画布
- imagettftext添加字体,并调整字体的位置,倾斜角度
生成像素点干扰,输出图像
//生成许多个像素点作为干扰
for($i=0;$i<200;$i++)
{
$color3 = imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),$color3);
}
//显示图像
imagepng($img);
//销毁图像
imagedestroy($img);
- 循环输出像素点
- 显示png格式图像
- 销毁图像
这篇博客介绍了如何使用PHP创建一个包含随机4位字符的图像验证码。首先,通过array_merge和shuffle函数生成并打乱字符数组,选取前4位作为验证码。接着,创建一个空画布,分配背景和字体颜色,绘制矩形,使用TTF字体写入验证码。然后添加干扰像素点,并最终输出PNG格式的图像。最后,博客提供了源代码链接。
589

被折叠的 条评论
为什么被折叠?



