GD 庫是 PHP 處理圖片(驗證碼、縮圖、水印、繪圖)的核心擴展。本文提供 Windows 與各 Linux 發行版的啟用/安裝步驟,並列出常用 GD 函數速查表。
Windows 啟用
- 開啟
php.ini。
- 尋找
;extension=php_gd2.dll(PHP 7+ 為 ;extension=gd)。
- 移除前面分號
;,儲存。
- 重啟 Apache / Nginx / PHP-FPM。
- 用
php -m | findstr gd 或 phpinfo() 確認載入。
Linux 安裝
| 發行版 | 安裝指令 |
| Debian/Ubuntu | apt-get install php-gd (或 php7.4-gd, php8.1-gd) |
| CentOS/RHEL/Fedora | yum install php-gd / dnf install php-gd |
| openSUSE | zypper install php7-gd |
| Alpine | apk add php8-gd |
| 原始碼編譯 | ./configure --with-gd ... (PHP 7.4+ 為 --enable-gd) |
驗證安裝
php -m | grep -i gd
php -i | grep -i gd
# 或建立 info.php: <?php phpinfo(); ?>
常用 GD 函數速查
| 函數 | 用途 |
imagecreatetruecolor() | 建立真彩色畫布(推薦取代 imagecreate()) |
imagecolorallocate() | 分配顏色 |
imagestring()/imagettftext() | 繪製字串(TTF 支援中文) |
imagecopyresampled() | 高品質縮放複製 |
imagepng()/imagejpeg()/imagegif() | 輸出圖片 |
imagedestroy() | 釋放記憶體 |
imagesetpixel()/imageline()/imageellipse() | 繪製像素/線/圓 |
imagefilter() | 濾鏡效果(灰階、模糊、銳化) |
常見問題
- 中文亂碼:需載入 TTF 字體(
imagettftext()),確保字體檔路徑正確、Web Server 有讀取權限。
- 記憶體不足:大圖處理調大
memory_limit 或分塊處理。
- 動畫 GIF:GD 不支援輸出動畫 GIF,需用
Imagick 或 GifFrameExtractor。
copyright ©
萬盛學電腦網 all rights reserved