gd庫是php最常用的圖片處理庫之一(另外一個是imagemagick),可以生成圖片、驗證碼、水印、縮略圖等等。要使用gd庫首先需要開啟gd庫擴展,
windows系統下需要在php.ini中將extension=php_gd2.dll 前邊的分號去掉然后重啟web服務器,
linux系統下一般在編譯php時已經開啟gd庫擴展,要是沒有開啟gd庫擴展則需要先編譯安裝freetype ,jpegsrc,libpng再用phpize安裝擴展庫進行編譯安裝。
圖像生成:
<?php /* 用windows畫圖板畫圖 1.新建空白畫布(指定寬高) 2.創建顏料.(紅,r 綠g 藍b,三原色組成的. 三原色由弱到強各可以選0-255之間) 3.畫線,寫字,畫圖形,填充等 4.保存/輸出圖片 5.銷毀畫布 */ //用gd庫來畫圖,仍是以上5個步驟. // 1:造畫布,以資源形式返回 imagecreatetruecolor(寬,高); $im = imagecreatetruecolor(300,200); // 2: 創建顏料 imagecolorallocate(畫布, 紅,綠,藍) $gray = imagecolorallocate($im,100,100,100); // 3: 填充畫布 imagefill($im,0,0,$gray); // 4: 保存成圖片 imagepng(畫布 [, 保存位置 ]),imagejpeg(),imagegif() header('content-type:image/jpeg'); imagepng($im); // 5: 銷毀畫布 銷毀畫面 imagedestroy(畫布) imagedestroy($im); ?>
縮率圖
<?php /* 步驟: 1.打開圖片源文件資源 2.獲得源文件的寬高 3.使用固定的公式計算新的寬高 4.生成目標圖像資源 5.進行縮放 6.保存圖像 7.釋放資源 */ //1.打開圖片源文件資源 $im = imagecreatefromjpeg('./bg.jpg'); //2.獲得源文件的寬高 $fx = imagesx($im); // 獲取寬度 $fy = imagesy($im); // 獲取高度 //3.使用固定的公式計算新的寬高 $sx = $fx/2; $sy = $fy/2; //4.生成目標圖像資源 $small = imagecreatetruecolor($sx,$sy); //5.進行縮放 imagecopyresampled($small,$im,0,0,0,0,$sx,$sy,$fx,$fy); //6.保存圖像 if(imagejpeg($small,'./sbg.jpg')) { echo '保存成功'; } else { echo '保存失敗'; } //7.釋放資源 imagedestroy($im); imagedestroy($small); ?>
水印生成
<?php /* 步驟: 1.分別創建大小圖畫布並獲取它們的寬高 2.添加文字水印 3.執行圖片水印處理 4.輸出 5.銷毀畫布 */ //1.分別創建大小圖畫布並獲取它們的寬高 $big = imagecreatefromjpeg('./bg.jpg'); $bx = imagesx($big); $by = imagesy($big); $small = imagecreatefrompng('./tu.png'); $sx = imagesx($small); $sy = imagesy($small); //2.添加水印文字 $blue = imagecolorallocate($big,0,0,255); imagettftext($big,16,0,100,100,$blue,'./msyh.ttf','驕傲的少年'); //3.執行圖片水印處理 imagecopymerge($big,$small,$bx-$sx,0,0,0,$sx,$sy,37); //4.輸出到瀏覽器 header('content-type: image/jpeg'); imagejpeg($big); //5.銷毀畫布 imagedestroy($big); imagedestroy($small); ?>
驗證碼
<?php /* 步驟: 1.創建畫布 2.造顏料 3.填充背景顏色 4.畫干擾點 5.畫噪點 6.寫字符串 7.輸出圖片 8.銷毀畫布 */ //1.創建畫布 $im=imagecreatetruecolor(50, 30); //2.造顏料 $gray = imagecolorallocate($im,30,30,30); $red = imagecolorallocate($im,255,0,0); $blue = imagecolorallocate($im, 100, 255, 255); //3.填充背景顏色 imagefill($im,0,0,$blue); //4.畫干擾點 for ($i=0; $i <4 ; $i++) { imageline($im, rand(0,20),0,100,rand(0,60),$red); } //5.畫噪點 for($i=0;$i<100;$i++){ imagesetpixel($im,rand(0,50),rand(0,30),$gray); } //6.寫字符串 $str=substr(str_shuffle('ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'),0,4); imagestring($im,5,5,5,$str,$red); //7.輸出圖片 header('content-type:image/png'); imagepng($im); //8.銷毀畫布 imagedestroy($im); ?>
在使用過程中。如果只是需要輸出圖片。可以使用 imagepng() 的第二個參數。比如
imagepng($im,'圖片存儲路徑');