實驗環境:wampserver集成開發環境包
源代碼:
<?php
//簡單使用GD繪製驗證碼 需要加載PHP_gd2.dll文件
// session_start();
/*
* 功能:給出隨機長度的字符
* 參數 :
* $len -給定字符串的長度
* 輸出:隨機給定長度的字符串
* */
header ( "content-type:image/gif" );
function random($len) {
$srcstr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$strs = "";
for($i = 0; $i < $len; $i ++) {
$strs .= $srcstr [mt_rand ( 0, 60 )]; //mt_rand 生成更好的隨機數
}
// return strtoupper ( $strs ); //將字符串轉化爲大寫字母
return $strs ;
}
$str = random ( 4 );
$width = 120;
$height = 35;
$image = imagecreate ( $width, $height ); //創建圖像
$back = imagecolorallocate ( $image, 0xFF, 0xFF, 0xFF ); //設置背景顏色
$font = imagecolorallocate ( $image, 287, 330, 347 ); //繪製模糊作用點
$font_color = imagecolorallocate ( $image, mt_rand ( 50, 120 ), mt_rand ( 50, 120 ), mt_rand ( 50, 120 ) ); //設置字體顏色
for($i = 0; $i < 500; $i ++) {
//畫一個單一像素
imagesetpixel ( $image, mt_rand ( 0, $width ), mt_rand ( 0, $height ), imagecolorallocate ( $image, mt_rand ( 1, 255 ), mt_rand ( 1, 255 ), mt_rand ( 1, 255 ) ) );
}
$font_file = $_SERVER['DOCUMENT_ROOT'].'arial.ttf'; //獲取字體的文件位置
//設置字體的位置和顏色
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 5, 30, $font_color, $font_file, substr($str,0,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 35, 30, $font_color, $font_file, substr($str,1,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 65, 30, $font_color, $font_file, substr($str,2,1));
imagettftext($image, mt_rand(15,28), mt_rand(-30,30), 95, 30, $font_color, $font_file, substr($str,3,1));
imagerectangle($image, 0, 0, $width-1, $height-1, $font);
imagepng($image); //顯示
imagedestroy($image); //結束
?>
檢測是否加載GD庫的方法:
新建一個test.php文件
<?php
echo phpinfo();
?>
在瀏覽器中訪問該文件的地址,查找是否存在下圖內容:
如果存在,恭喜你!你已經能夠成功運行上面的程序。
如果不存在上圖內容:找到php的配置文件php.ini搜索gd關鍵詞去掉前面的;