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

来源:互联网 发布:淘宝药品必须货到付款 编辑:程序博客网 时间:2024/05/21 16:21
<?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); ?>



效果展示:


原创粉丝点击