首页 > 开发 > Php > 正文

最新最全PHP生成制作验证码代码详解(推荐)

2020-02-21 21:04:13
字体:
来源:转载
供稿:网友

1.0  首先先看代码

<?phpheader("Content-Type:text/html;Charset=UTF-");// 设置页面的编码风格header("Content-Type:image/jpeg");// 通知浏览器输出的是jpeg格式的图像$img = imagecreatetruecolor(,);//创建画布并设置大小 x轴 y轴$bgcolor = imagecolorallocate($img, mt_rand(,), mt_rand(,), mt_rand(,));//分配背景颜色imagefill($img, , , $bgcolor); ////把背景填充到图像imagejpeg($img); // 输出图像imagedestroy($img); // 销毁图像?> 

好,现在结合以上代码,来分析分析以上用到的几个函数:

①  imagecreatetruecolor();

imagecreatetruecolor — 新建一个真彩色图像(感觉哇,那么长,其实仔细一看挺好记的 image/create/true/color,什么是真彩色图像?往下看)

resource imagecreatetruecolor ( int $width , int $height )

imagecreatetruecolor() 和 imagecreate()两个函数都能创建画布

resource imagecreate ( int $x_size , int $y_size ) 

imagecreatetruecolor()建立的是一幅大小为 x和 y的黑色图像(默认为黑色[即便叫法就是真彩色图像]),如想改变背景颜色则需

要用填充颜色函数 imagefill($img,0,0,$color);

imagecreate 新建一个空白图像资源,用imagecolorAllocate()添加背景色

上面两个函数只不过是一个功能的两种方法

②  imagecolorallocate();

imagecolorallocate — 为一幅图像分配颜色

int imagecolorallocate ( resource $image , int $red , int $green , int $blue )

颜色分别用 红 绿 蓝三色组合,这些参数是 0 到 255 的整数或者十六进制的 0x00 到 0xFF。

③  mt_rand();

mt_rand — 生成更好的随机数

int mt_rand ( int $min , int $max )

$min 可选的、返回的最小值(默认:0)  $max 可选的、返回的最大值(默认:mt_getrandmax())
这里就是用来让他随机生成背景颜色,0-255随便取值。所以页面没刷新一次画布背景颜色就不一样。效果图:

2.0  开始往里面做干扰线,干扰点。防止验证图像被秒识别

<?phpheader("Content-Type:text/html;Charset=UTF-");// 设置页面的编码风格header("Content-Type:image/jpeg");// 通知浏览器输出的是jpeg格式的图像$img = imagecreatetruecolor(,);//创建画布并设置大小 x轴 y轴$bgcolor = imagecolorallocate($img, mt_rand(,), mt_rand(,), mt_rand(,));//分配背景颜色//添加干扰线,并循环次,背景颜色随机for($i=;$i<;$i++){$linecolor = imagecolorallocate($img,mt_rand(,),mt_rand(,),mt_rand(,));imageline($img, mt_rand(,), mt_rand(,), mt_rand(,), mt_rand(,), $linecolor);}//添加干扰点,并循环次,背景颜色随机for($i=;$i<;$i++){$dotcolor = imagecolorallocate($img, mt_rand(,), mt_rand(,), mt_rand(,));imagesetpixel($img, mt_rand(,), mt_rand(,), $dotcolor);}imagefill($img, , , $bgcolor); ////把背景填充到图像imagejpeg($img); // 输出图像imagedestroy($img); // 销毁图像?>             
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表