1 //验证码 2 function _code($_width = 75, $_height = 25) { 3 //随机字符 4 for ($i = 0; $i < 4; $i++) { 5 $_num .= dechex(mt_rand(0, 15)); 6 } 7 8 $_SESSION['code'] = $_num; 9 //创建图像 10 $im = imagecreatetruecolor($_width, $_height); 11 12 //填充背景色 13 $bg_color = imagecolorallocate($im, 250, 250, 250); 14 imagefill($im, 0, 0, $bg_color); 15 //四条随机线条 16 for ($i = 0; $i < 6; $i++) { 17 $linecolor = imagecolorallocate($im, mt_rand(150, 255), mt_rand(150, 200), 18 mt_rand(150, 200)); //线条颜色 19 imageline($im, mt_rand(1, $_width), mt_rand(1, $_height), mt_rand(1, $_width), 20 mt_rand(1, $_height), $linecolor); 21 } 22 23 //随机噪点 24 for ($i = 0; $i < 1000; $i++) { 25 $dotcolor = imagecolorallocate($im, mt_rand(200, 255), mt_rand(200, 255), 26 mt_rand(200, 255)); //噪点颜色 27 imagesetpixel($im, mt_rand(0, $_width), mt_rand(0, $_height), $dotcolor); 28 } 29 30 //写入字符 31 for ($i = 0; $i < strlen($_SESSION['code']); $i++) { 32 $txtcolor = imagecolorallocate($im, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 33 100)); //字符颜色 34 imagestring($im, mt_rand(3, 5), $i * $_width / 4 + mt_rand(1, 10), mt_rand(1, $_height / 35 2), $_SESSION['code'][$i], $txtcolor); 36 } 37 //输出图像 38 header('Content-Type: image/png'); 39 imagepng($im); 40 41 //销毁 42 imagedestroy($im); 43 }