天天看点

GD库 验证码函数

慕课网后 端开发PHP教程-->PHP进阶篇--GD库图像处理-->http://www.imooc.com/learn/701-->2-5 验证码函数的封装及测试

<?php
header("content-type:text/html;charset=utf-8");
function getVerify($type=3,$length=6,$codeName='code',$pixel=100,$line=0,$arc=0,$width=200,$height=50,$fontFile='fonts/7.ttf'){

	//创建画布
	$image=imagecreatetruecolor($width,$height);
	//创建颜色
	$white=imagecolorallocate($image,255,255,255);
	//创建填充矩形
	imagefilledrectangle($image,0,0,$width,$height,$white);

	function getRandColor($image){
		return imagecolorallocate($image,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
	}

	/**默认4位数字
	* 1-数字    * 2-字母   *3-数字+字母    * 汉字
	*/
	switch($type){
		case 1:  //数字
			$string=str_shuffle(join('',array_rand(range(0,9),$length)));
			break;
		case 2:  //字母
			$string=str_shuffle(join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'))),$length)));
			break;
		case 3:  //数字+字母
			$string=str_shuffle(join('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'),range(0,9))),$length)));
			break;
		case 4:  //汉字
			$str="勇,担,金,砖,责,任,维,护,世,界,和,平,宁,国,家,要,联,合,宪,章,宗,旨,原,则,以,及,际,关,系,基,本,准,坚,定,多,边,主,义,推,动,民,化,反,对,霸,权,强,政,治,倡,导,共,同,综,作,可,持,续,的,安,全,观,建,设,性,参,与,地,缘,热,点,问,题,解,决,进,程,发,挥,应,有,用";
			$arr=explode(',',$str);
			$string=str_shuffle(join('',array_rand(array_flip($arr),$length)));
			break;
		default:  
			exit('非法操作');
			break;
	}
	session_start();
	$_SESSION[$codeName]=$string;

	for($i=0;$i<$length;$i++){
		$size=mt_rand(20,28);
		$angle=mt_rand(-15,15);
		$x=ceil($width/$length)*$i+imagefontwidth($size);//50+30*$i;
		$y=mt_rand($height/2,$height-imagefontheight($size));//30;
		$color=getRandColor($image);

		$text=mb_substr($string,$i,1,'utf-8');
		
		imagettftext($image,$size,$angle,$x,$y,$color,$fontFile,$text);
	}
	///添加干扰点
	if($pixel>0){
		for($i=1;$i<=$pixel;$i++){
			imagesetpixel($image,mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
		}
	}

	//添加干扰线
	if($line>0){
		for($i=1;$i<=$line;$i++){
			imageline($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width),mt_rand(0,$height),getRandColor($image));
		}
	}

	//添加圆弧
	if($arc>0){
		for($i=1;$i<=$arc;$i++){
			imagearc($image,mt_rand(0,$width),mt_rand(0,$height),mt_rand(0,$width/2),mt_rand(0,$height/2),mt_rand(0,360),mt_rand(0,360),getRandColor($image));
		}
	}

	//告诉浏览器以图片的形式显示
	header("content-type:image/jpeg");
	//imagejpeg($image) 输出图像
	imagejpeg($image);
	//销毁资源
	imagedestroy($image);


}


getVerify();

?>