| 格式 | 全稱 | 特點 | 適用場景 | PHP 函數族 |
| PNG | Portable Network Graphics | 無損壓縮、支援 Alpha 透明、24/48 位色彩、漸進顯示 | Web 圖標、截圖、需透明背景的圖片 | imagecreatefrompng, imagepng |
| JPEG | Joint Photographic Experts Group | 有損壓縮、24 位色彩、壓縮率高、不支援透明 | 照片、複雜色彩圖片、網頁傳輸優化 | imagecreatefromjpeg, imagejpeg |
| GIF | Graphics Interchange Format | LZW 無損、256 色、支援動畫、單色透明 | 簡單動畫、小圖標、舊項目兼容 | imagecreatefromgif, imagegif |
| WBMP | Wireless Bitmap | 1 位雙色(黑白)、極小體積 | WAP 頁面、極低帶寬設備 | imagecreatefromwbmp, imagewbmp |
| XBM | X BitMap | C 源碼格式、單色、文本可讀、瀏覽器原生支援 | 簡單圖標、嵌入式設備 | imagecreatefromxbm, imagexbm |
| 類型 | 描述 | PHP 函數 |
| 內建點陣字體 | 1~5 號固定大小,無需外部文件 | imagestring, imagestringup |
| TrueType (TTF) | 可縮放矢量字體,支援抗鋸齒、多語言 | imagettftext, imagettfbbox |
| PostScript Type 1 | 印刷級字體,專業排版使用 | imagepsloadfont, imagepstext(PHP 7.0 移除) |
關鍵函數速查
// 創建畫布
$im = imagecreatetruecolor($width, $height); // 真彩色
$im = imagecreate($width, $height); // 調色板模式(舊版)
// 顏色分配
$color = imagecolorallocate($im, $r, $g, $b);
$color = imagecolorallocatealpha($im, $r, $g, $b, $alpha); // 含透明度
// 繪圖基礎
imagesetpixel($im, $x, $y, $color);
imageline($im, $x1, $y1, $x2, $y2, $color);
imagerectangle($im, $x1, $y1, $x2, $y2, $color);
imagefilledrectangle($im, $x1, $y1, $x2, $y2, $color);
imagearc($im, $cx, $cy, $w, $h, $start, $end, $color);
imagefilledarc($im, $cx, $cy, $w, $h, $start, $end, $color, IMG_ARC_PIE);
// 文字繪製
imagestring($im, $font, $x, $y, $text, $color); // 內建字體
imagettftext($im, $size, $angle, $x, $y, $color, $fontfile, $text); // TTF
// 輸出/保存
imagepng($im, $filename, $quality, $filters);
imagejpeg($im, $filename, $quality);
imagegif($im, $filename);
imagedestroy($im); // 釋放內存
實戰建議
- 優先使用 PNG:無損、透明、現代瀏覽器完美支援
- 照片用 JPEG:
imagejpeg($im, null, 85) 平衡品質與體積
- 避免 GIF:專利歷史包袱、色彩受限、動畫場景改用 APNG/WebP
- TTF 字體佈局:使用
imagettfbbox() 計算文本邊界框,實現精準對齊、換行、排版
- 內存管理:大圖處理後及時
imagedestroy(),長時間運行腳本需監控 memory_limit
- 現代替代:ImageMagick (Imagick 擴展) 功能更強、格式更全、性能更優,複雜圖像處理首選
- 上一篇文章: Linux 環境下 PHP 新聞發布系統架構設計
- 下一篇文章: PHP 數學庫開發指南:以線性回歸為例
Copyright ©
程式碼之家 All Rights Reserved