效果如图:
步骤如下:
1.获取随机验证码
用getcode函数(自定义),它会返回一个字符串.
2.创建一个图像资源、分配颜色
$m = imagecreatetruecolor($width,$height);
imagecolorallocate,这个其实就是获取一种颜色
3.开始绘画
1).在image图像左上角处开始区域填充背景颜色
imagefill($m,0,0,$bg);
2).添加一个有颜色的矩形框
imagerectangle
3).添加干扰点和干扰线
4).把获取到的验证码字符串画上图像上去
4.输出图像
1).直接输出到浏览器
//注意此函数执行前不能有输出,空格也不行
//如果没有设置响应头,则页面会出现乱码,而不是一张验证码的图像
header(“content-type:image/png”); //设置响应头信息
imagepng($m);
2).输出到文件中
imagepng($m,'test.png');
5.销毁图像
imagedestroy($m);
代码如下:
/** * @param int $num 验证码的个数,默认为4 * @param int $type 验证码的类型,0:纯数字,1:数字+小写字母 2:数字+大小写字母 * @param bool $outfile 验证码是否输出到文件中 * @return array 以数组形式返回验证码和验证码图片名字 */function drawidentifycode($num=4,$type=0,$outfile = true){ //绘制验证码$code = getcode($num,$type);//获取验证码$width = $num*35; $height = 40;//1.创建一个画图像资源、分配颜色$m = imagecreatetruecolor($width,$height); $c = array(imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)), imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)), imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255)), imagecolorallocate($m,rand(0,255),rand(0,255),rand(0,255))); $bg = imagecolorallocate($m,220,220,220); //背景颜色//2.开始绘画//在image图像左上角处开始区域填充 imagefill($m,0,0,$bg);//添加一个有颜色的矩形框 imagerectangle($m,0,0,$width-1,39,$c[0]);//添加干扰点for($i=0;$i400;$i++) imagesetpixel($m,rand(0,$width),rand(0,30),$c[$i%4]);//添加干扰线for($i=0;$i5;$i++) imageline($m,rand(0,$width),rand(0,30),rand(0,$width),rand(0,30),$c[$i%4]);//绘制验证码内容(一个一个字符绘制)for($i=0;$i$num;$i++) imagettftext($m,28,rand(-50,50),15+(28*$i),30,$c[$i%4],consola.ttf,$code[$i]);//3.输出图像$filename = null; if(!$outfile) { //注意此函数执行前不能有输出,空格也不行//如果没有设置响应头,则页面会出现乱码,而不是一张验证码的图像 header(content-type:image/png); //设置响应头信息 imagepng($m); } else { $filename = time().'.png'; imagepng($m,$filename); }//4.销毁图片 imagedestroy($m); return array($code,$filename);}/** * @function 随机生成一个验证码的函数 * @param $m: 验证码的个数(默认为4) * @param $type:验证码的类型:0:纯数字,1:数字+小写字母 2:数字+大小写字母 * @return 返回字符串形式的验证码 */function getcode($m=4,$type=0){ $str = 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz; $t = array(9,35,strlen($str)-1); //验证码类型//随机生成验证码所需内容$c = ; for($i=0;$i$m;$i++) $c.=$str[rand(0,$t[$type])]; return$c;}
').addclass('pre-numbering').hide(); $(this).addclass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadein(1700); }); }); 以上就介绍了 php如何生成验证码,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
