PHP圖片驗證碼實例

在網上看到一個圖片驗證碼,挻漂亮的,但是取回來發現,好像有點小問題,還是改爲自己的口味吧,很多時候,如果無法使用,應該是字體的問題。程序所用的字體win7 自帶的,需要上傳到web目錄

代碼:

複製代碼代碼如下:
/*
 *  @Author fy
 */

編輯整理:www.jbxue.com 

$imgwidth =100; //圖片寬度
$imgheight =40; //圖片高度
$codelen =4; //驗證碼長度
$fontsize =20; //字體大小
$charset = 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789';
$font = 'Fonts/segoesc.ttf';

$im=imagecreatetruecolor($imgwidth,$imgheight);

$while=imageColorAllocate($im,255,255,255);
imagefill($im,0,0,$while); //填充圖像

//取得字符串
$authstr='';
$_len = strlen($charset)-1;
for ($i=0;$i<$codelen;$i++) {
 $authstr .= $charset[mt_rand(0,$_len)];
}

session_start();
$_SESSION['scode']=strtolower($authstr);//全部轉爲小寫,主要是爲了不區分大小寫

//隨機畫點,已經改爲劃星星了
for ($i=0;$i<$imgwidth;$i++){
    $randcolor=imageColorallocate($im,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
 imagestring($im,mt_rand(1,5), mt_rand(0,$imgwidth),mt_rand(0,$imgheight), '*',$randcolor);
    //imagesetpixel($im,mt_rand(0,$imgwidth),mt_rand(0,$imgheight),$randcolor);
}
//隨機畫線,線條數量=字符數量(隨便)
for($i=0;$i<$codelen;$i++) 
{  
 $randcolor=imagecolorallocate($im,mt_rand(0,255),mt_rand(0,255),mt_rand(0,255));
 imageline($im,0,mt_rand(0,$imgheight),$imgwidth,mt_rand(0,$imgheight),$randcolor); 
}

$_x=intval($imgwidth/$codelen); //計算字符距離
$_y=intval($imgheight*0.7); //字符顯示在圖片70%的位置
for($i=0;$i<strlen($authstr);$i++){

 $randcolor=imagecolorallocate($im,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150));
 //imagestring($im,5,$j,5,$imgstr[$i],$color3);
 // imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
 imagettftext($im,$fontsize,mt_rand(-30,30),$i*$_x+3,$_y,$randcolor,$font,$authstr[$i]);

}

//生成圖像
header("content-type:image/PNG");
imagePNG($im);
imageDestroy($im);

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