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();

?>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章