PHP 建立動態圖像並不複雜,只要正確配置環境並掌握核心函式,即可輕鬆產生圖表、驗證碼、縮圖等應用。本文將詳細說明 GD 庫的安裝步驟、基本繪圖流程,並提供建立純色圖片與縮圖的完整程式碼範例。
在使用 GD 繪圖函式前,必須先安裝以下三個元件,且須嚴格遵循順序:
安裝完成後,需重新編譯 PHP。若採用 DSO 模式安裝,執行 make clean 後,在 configure 參數中加入:
--with-gd=[/path/to/gd]
--with-jpeg-dir=[/path/to/jpeg-6b]
--with-t1lib=[/path/to/t1lib]
接著執行 make 和 make install,重啟 Apache,透過 phpinfo() 確認 GD 區塊已啟用。
以下範例建立一張 250×250 像素的天藍色 PNG 圖片:
<?php
// 1. 送出正確的 MIME 標頭
header('Content-Type: image/png');
// 2. 建立空白畫布
$newImg = imagecreate(250, 250);
// 3. 分配顏色 (RGB: 136, 193, 255)
$skyblue = imagecolorallocate($newImg, 136, 193, 255);
// 4. 填滿背景
imagefill($newImg, 0, 0, $skyblue);
// 5. 輸出圖片並釋放資源
imagepng($newImg);
imagedestroy($newImg);
?>
將上述程式碼存為 skyblue.php,瀏覽器訪問即可看到天藍色方塊。
利用 imagecopyresized() 將大圖縮放為 35×35 的縮圖:
<?php
header('Content-Type: image/png');
$newWidth = 35;
$newHeight = 35;
// 建立目標空白圖
$newImg = imagecreate($newWidth, $newHeight);
// 載入原始圖 (假設為 test.png)
$origImg = imagecreatefrompng('test.png');
// 執行縮放複製
imagecopyresized(
$newImg, $origImg,
0, 0, 0, 0,
$newWidth, $newHeight,
imagesx($origImg), imagesy($origImg)
);
// 輸出並清理
imagepng($newImg);
imagedestroy($newImg);
imagedestroy($origImg);
?>
儲存為 resized.php 並訪問,即可獲得縮放後的 PNG 圖片。
掌握 GD 庫的安裝順序、基本繪圖流程(建立畫布→分配顏色→繪製→輸出→釋放)以及 imagecopyresized() 縮圖技巧,即可滿足大多數動態圖像需求。後續可進一步學習 TrueType 字型繪製、多邊形繪圖、漸層填充等進階功能。