实现步骤
- 生成指定宽高的画布
- 准备好字好需要生成的字符串
- 每次执行,让背景填充随机的颜色(浅色系)
- 在画布上画上随机的干扰元素(随机点、随机线、随机弧形等均可,但不可过份影响用户的视觉)
- 写上4个文字
- 输出header头,告知浏览器按照某类型显示
- 输出图像
- 销毁图像资源
具体
1、准备随机数
//没有0,i,l,o
$str = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789';
$str = str_shuffle($str);
$string = substr($str,0 ,3);
2、填充验证
背景浅一些颜色【130-255】,文字深色【0-130】
//浅色的背景函数
function randBg($img) {
return imagecolorallocate($img, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
}
//深色函数,深色的字或者点这些干 扰元素
function randPix($img) {
return imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
}
3、随机干扰元素
//画干扰元素
for ($i = 0; $i < 50; $i++) {
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), randPix($img));
}
4、写上文字
for ($i = 0; $i < $num; $i++) {
$x = floor($width / $num) * $i;
$y = mt_rand(0, $height - 15);
imagechar($img, 5, $x, $y, $string[$i], randPix($img));
}
5、输出header头。告知浏览器类型
$imagetype = 'png';
$header = 'Content-type:image/' . $imagetype;
6、销毁资源,返回字符
imagedestroy($img);
实例代码
check_code();
function check_code($width = 100, $height = 50, $num = 4, $type = 'jpeg') {
$img = imagecreate($width, $height);
$string = '';
for ($i = 0; $i < $num; $i++) {
$rand = mt_rand(0, 2);
switch ($rand) {
case 0:
$ascii = mt_rand(48, 57); //0-9
break;
case 1:
$ascii = mt_rand(65, 90); //A-Z
break;
case 2:
$ascii = mt_rand(97, 122); //a-z
break;
}
//chr()
$string .= sprintf('%c', $ascii);
}
//背景颜色
imagefilledrectangle($img, 0, 0, $width, $height, randBg($img));
//画干扰元素
for ($i = 0; $i < 50; $i++) {
imagesetpixel($img, mt_rand(0, $width), mt_rand(0, $height), randPix($img));
}
//写字
for ($i = 0; $i < $num; $i++) {
$x = floor($width / $num) * $i + 2;
$y = mt_rand(0, $height - 15);
imagechar($img, 5, $x, $y, $string[$i], randPix($img));
}
//imagejpeg
$func = 'image' . $type;
$header = 'Content-type:image/' . $type;
if (function_exists($func)) {
header($header);
$func($img);
} else {
echo '图片类型不支持';
}
imagedestroy($img);
return $string;
}
//浅色的背景
function randBg($img) {
return imagecolorallocate($img, mt_rand(130, 255), mt_rand(130, 255), mt_rand(130, 255));
}
//深色的字或者点这些干 扰元素
function randPix($img) {
return imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
}