php.ini 取消註釋 extension=gd(PHP 7.2+)或 extension=php_gd2.dll,重啟服務。phpinfo() 檢查 GD 版本、支持格式。
| 分類 | 代表函數 | 用途 |
|---|---|---|
| 基本信息 | gd_info, imagetypes, getimagesize, imagesx, imagesy, imagecolorat | 庫版本、支持格式、圖片尺寸、像素顏色 |
| 圖像轉換 | imagejpeg, imagepng, imagegif, imagewebp, imagebmp | 格式互轉、輸出 |
| 創建/銷毀 | imagecreatetruecolor, imagecreatefromjpeg/png/gif/webp, imagedestroy | 畫布創建、從文件/字符串加載、釋放資源 |
| 繪圖操作 | imageline, imagerectangle, imageellipse, imagearc, imagepolygon, imagesetthickness | 線、矩形、橢圓、弧、多邊形、線寬 |
| 圖像操作 | imagecopy, imagecopyresampled, imagefilter, imagerotate, imageflip, imagecrop | 複製、縮放重採樣、濾鏡、旋轉、翻轉、裁剪 |
| 圖像設置 | imagesavealpha, imagealphablending, imagecolortransparent, imagefill, imagefilledrectangle | 透明度、混合模式、填充色、透明色 |
| 文字繪製 | imagestring, imagettftext, imageftbbox, imagettfbbox | 內置字體/TrueType 字體繪文、計算邊界框 |
| 輸出輸出 | imagejpeg/png/gif/webp/bmp, image2wbmp, header() 設置 Content-Type | 輸出到瀏覽器或文件 |
print_r(gd_info());
/* 輸出示例
Array (
[GD Version] => bundled (2.1.0 compatible)
[FreeType Support] => 1
[JPEG Support] => 1
[PNG Support] => 1
[GIF Read Support] => 1
[GIF Create Support] => 1
[WebP Support] => 1
...
) */
if (imagetypes() & IMG_PNG) echo "支持 PNG";
$info = getimagesize("photo.jpg");
// [0]=寬, [1]=高, [2]=類型常量, [3]="width=... height=..."
// 類型常量:IMAGETYPE_JPEG=2, IMAGETYPE_PNG=3, IMAGETYPE_GIF=1...
$im = imagecreatefrompng("test.png");
echo "寬: " . imagesx($im) . " 高: " . imagesy($im);
$rgb = imagecolorat($im, 100, 100);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
imagecreatefromjpeg() 加載源圖imagecreatetruecolor() 創建目標畫布imagecopyresampled() 高質量縮放imagettftext() 繪制水印文字header('Content-Type: image/jpeg') + imagejpeg() 輸出imagedestroy() 釋放兩個資源imagedestroy() 導致內存洩漏imagecreate) 不支持透明、抗鋸齒GDFONTPATHContent-Type,且無任何輸出(含 BOM、空白)