您的位置:首页 > 编程语言 > PHP开发

应用PHP GD库中图像处理函数制作验证码

2017-07-15 10:10 447 查看
<?php
//开启session,之后会把验证码存入session,然后在后端与用户输入的验证码对比
session_start();
//新建一个真彩色图像
$image=imagecreatetruecolor(100, 30);
//定义白色
$bgcolor=imagecolorallocate($image, 255, 255, 255);
//填充颜色
imagefill($image,0,0,$bgcolor);
//验证码字符串
$verify_str='';
//循环产生四位字符
for ($i=0; $i < 4; $i++) {
//设置字体
$font='img/msyh.ttc';
$fontsize=16;
//随机颜色
$fontcolor=imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
$contentstr='23456789acefghijkmpqrstvwxyz';
//截取字符
$fontcontent=substr($contentstr,mt_rand(0,strlen($contentstr)-1),1);
$verify_str.=$fontcontent;
//随机位置
$x=($i*100/4)+mt_rand(5,10);
$y=mt_rand(20,25);
//将文字写进图中
imagettftext($image, $fontsize, mt_rand(-30,30), $x, $y, $fontcolor, $font, $fontcontent);
}

//中文验证码
/*for ($i=0; $i < 4; $i++) {
$font='img/msyh.ttc';
$fontsize=10;
$fontcolor=imagecolorallocate($image, mt_rand(0,120), mt_rand(0,120), mt_rand(0,120));
$contentstr='这是一段话';
$fontcontent=mb_substr($contentstr,mt_rand(0,strlen($contentstr)/3-1),1,"utf-8");
$verify_str.=$fontcontent;
$x=($i*100/4)+mt_rand(5,10);
$y=mt_rand(20,25);
imagettftext($image, $fontsize, mt_rand(-30,30), $x, $y, $fontcolor, $font, $fontcontent);
}*/

//把字符串存入session
$_SESSION['verify']=$verify_str;
//制作干扰项 200个点  三条线
for ($i=0; $i <200 ; $i++) {
$pointcolor=imagecolorallocate($image,mt_rand(50,200),mt_rand(50,200),mt_rand(50,200));
imagesetpixel($image, mt_rand(1,99), mt_rand(1,29), $pointcolor);
}
for ($i=0; $i < 3; $i++) {
$linecolor=imagecolorallocate($image, mt_rand(80,220), mt_rand(80,220), mt_rand(80,220));
imageline($image, mt_rand(1,99), mt_rand(1,29), mt_rand(1,99), mt_rand(1,29), $linecolor);
}
//设置头信息,告诉浏览器输出的内容是图像
header('Content-type:image/png');
//输出图片
imagepng($image);
//销毁图像  释放与 image 关联的内存。
imagedestroy($image);
?>


效果展示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: