PHP图片验证码生成示例
一、显示效果
二、代码如下
复制代码 代码如下:/*
* @Author fy
*/
$imgwidth =100; //设置图片宽度 $imgheight =40; //设置图片高度 $codelen =4; //设定验证码长度 $fontsize =20; //指定字体大小 $charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; $font = 'Fonts/segoesc.ttf'; //指定字体文件路径
$im=imagecreatetruecolor($imgwidth,$imgheight); //创建真彩色图像资源
$while=imageColorAllocate($im,255,255,255); imagefill($im,0,0,$while); //使用白色填充整个图像区域
//获取随机验证码字符串 $authstr=''; $_len = strlen($charset)-1; for ($i=0;$i<$codelen;$i++) { $authstr .= $charset[mt_rand(0,$_len)]; }
session_start(); $_SESSION['scode']=strtolower($authstr);//将验证码转为小写存入Session,以实现不区分大小写的验证逻辑
//随机绘制干扰元素,此处改为绘制星星图案 for ($i=0;$i<$imgwidth;$i++){ $randcolor=imageColorallocate($im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imagestring($im,mt_rand(1,5), mt_rand(0,$imgwidth),mt_rand(0,$imgheight), '*',$randcolor); //imagesetpixel($im,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$randcolor); } //随机绘制干扰线,线条数量等于字符数量 for($i=0;$i<$codelen;$i++) { $randcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255)); imageline($im,0,mt_rand(0,$imgheight),$imgwidth,mt_rand(0,$imgheight),$randcolor); }
$_x=intval($imgwidth/$codelen); //计算每个字符的水平间距
$_y=intval($imgheight*0.7); //设定字符垂直位置在图片高度的70%处
for($i=0;$i<strlen($authstr);$i++) {
$randcolor=imagecolorallocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)); //imagestring($im,5,$j,5,$imgstr[$i],$color3); // imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text ) imagettftext($im,$fontsize,mt_rand(-30,30),$i*$_x+3,$_y,$randcolor,$font,$authstr[$i]);
}
//输出图像 header("content-type:image/PNG"); imagePNG($im); imageDestroy($im); //销毁图像资源