<?php //设置session,用与存放验证码 session_start();
//创建图片并设置图片大小 $image = imagecreatetruecolor(100, 30);
//设置验证码颜色
// 方法 imagecolorallocate(图片对象, int red, int green, int blue); $bgcolor = imagecolorallocate($image,190,234,239); //设置为白色
//区域填充
//方法 imagefill(图片对象, int x, int y, 颜色)
//(x,y) 所在的区域着色,col 表示欲涂上的颜色
imagefill($image, 0, 0, $bgcolor); // 设置验证码变量
$captcha_code = "";
//生成随机数字
for($i=0;$i<4;$i++){
//设置字体大小 $fontsize = 6; //设置字体颜色,随机颜色
//rand() 为PHP 中的随机函数 标识 从 0开始 到 120 的范围随机
//0-120深颜色
$fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //设置数字 $fontcontent = rand(0,9); //连续定义变量
$captcha_code .= $fontcontent; //设置当前字出现的位置 $x = ($i*100/4)+rand(5,10);
$y = rand(5,10);
// 将文字写入到图片中
//imagestring(图片对象,字体大小,x坐标,y坐标,文字类容,字体颜色); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor);
}
//存到session
$_SESSION['authcode'] = $captcha_code;
//增加干扰元素,设置雪花点
for($i=0;$i<200;$i++){
//设置点的颜色,50-200颜色比数字浅,不干扰阅读
$pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200));
//imagesetpixel — 画一个单像素 的点//imagesetpixel(图片对象,x坐标,y坐标,颜色)
imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor);
}
//增加干扰元素,设置横线
for($i=0;$i<4;$i++){
//设置线的颜色
$linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220)); //设置线,两点一线//imageline(图片对象,起始x,起始y,结束x,结束y,颜色)
imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor);
}
//设置响应头为 图片响应 image/png header('Content-Type: image/png'); //imagepng() 压缩图片为 png格式 (矢量图) imagepng($image); //imagedestroy() 结束图形函数 销毁临时 图片对象 imagedestroy($image);