`
//PHP.ini文件error_reporting的默认配置会导致在使用$_SESSION输出显示乱码
//加上error_reporting(E_ALL & ~E_NOTICE); 来屏蔽错误
error_reporting(E_ALL & ~E_NOTICE);
$_width=75;
$_height=25;
$_rnd_code=4;
//创建随机码
for ($i=0;$i<$_rnd_code;$i++){
$_nmsg .=dechex(mt_rand(0,15)); //dechex 十进制转换为十六进制
}
//保存session
$_SESSION[‘code‘] = $_nmsg;
//创建一张图片
$_img=imagecreatetruecolor($_width, $_height);
//创建一个颜色
$_white=imagecolorallocate($_img, 255, 255, 255);
$_black=imagecolorallocate($_img, 6, 6, 6);
//填充 imagefill() 在 image 图像的坐标 x,y(图像左上角为 0, 0)处用 color 颜色执行区域填充(即与 x, y 点颜色相同且相邻的点都会被填充)。
imagefill($_img, 0, 0, $_white);
//随机画出6个线条
for($i=0;$i<6;$i++){
$_rnd_color=imagecolorallocate($_img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
imageline($_img, mt_rand(0, $_width), mt_rand(0, $_height), mt_rand(0, $_width), mt_rand(0, $_height), $_rnd_color);
}
//随机雪花
for ($i=0;$i<100;$i++){
$_rnd_color=imagecolorallocate($_img, mt_rand(200, 255), mt_rand(200, 255), mt_rand(200, 255));
imagestring($_img, 1, mt_rand(1, $_width), mt_rand(1, $_height), ‘*‘, $_rnd_color);
}
//输出验证码
for ($i=0;$i<4;$i++){
imagestring($_img,5,$i*$_width/$_rnd_code+mt_rand(1, 10),mt_rand(1, $_height/2), $_SESSION[‘code‘][$i],$_black);
}
//输出图像
header(‘Content-Type:image/png‘);
imagepng($_img);
`
原文:http://haixin.blog.51cto.com/1528212/1385032