首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP GD 庫動態圖像處理入門:畫布創建、繪圖、輸出與資源釋放完整流程

     編輯:PHP 相關知識

PHP GD 庫動態圖像處理入門:畫布創建、繪圖、輸出與資源釋放完整流程

PHP GD 擴展支持 JPEG、PNG、WBMP 格式圖像創建與操作(不再支持 GIF)。本文講解圖像生成四步驟、畫布管理函數、顏色分配、基本繪圖函數,並給出完整可運行示例。

支持格式說明

格式特點適用場景
JPEG有損壓縮、色彩豐富照片、複雜圖像
PNG無損壓縮、支持透明度圖標、截圖、需透明背景
WBMP無線位圖、單色早期移動設備(現極少用)

圖像生成四步驟

  1. 創建畫布:imagecreatetruecolor($width, $height)(真彩色)或 imagecreate()(調色板模式,舊版)。
  2. 分配顏色、繪製內容:imagecolorallocate()、imagefill()、imageline()、imagestring() 等。
  3. 輸出圖像:發送 Content-Type 頭,調用 imagepng()/imagejpeg()/imagewbmp()。
  4. 釋放資源:imagedestroy($im) 釋放內存,防止洩漏。

完整示例:藍底白線白字

<?php
// 1. 創建畫布
$width  = 200;
$height = 200;
$im = imagecreatetruecolor($width, $height);

// 2. 分配顏色
$white = imagecolorallocate($im, 255, 255, 255);
$blue  = imagecolorallocate($im, 0, 0, 64);

// 3. 繪製
imagefill($im, 0, 0, $blue);                    // 填充背景
imageline($im, 0, 0, $width, $height, $white);  // 對角線
imagestring($im, 4, 50, 150, 'Sales', $white);  // 字體 4,座標 (50,150)

// 4. 輸出
header('Content-type: image/png');
imagepng($im);

// 5. 釋放
imagedestroy($im);

畫布管理函數速查

函數說明
imagecreatetruecolor(w, h)創建真彩色畫布(推薦),支持 1670 萬色。
imagecreate(w, h)創建基於調色板畫布(256 色),兼容極舊代碼。
imagecolorallocate(im, r, g, b)分配顏色 ID,返回標識符供繪圖函數使用。
imagecolorallocatealpha(im, r, g, b, alpha)分配帶透明度顏色 (0=不透明, 127=全透明)。
imagefill(im, x, y, color)從 (x,y) 洪水填充顏色。
imagesetpixel(im, x, y, color)繪製單個像素。

常用繪圖函數分類

  • 幾何:imageline、imagerectangle、imagepolygon、imageellipse、imagearc。
  • 文本:imagestring(內置字體)、imagettftext(TrueType 字體,需 FreeType)、imagettfbbox(計算文本邊界)。
  • 圖像合成:imagecopy、imagecopyresized、imagecopyresampled(高質量縮放)、imagecopymerge(透明度合成)。
  • 濾鏡/效果:imagefilter(灰度、銳化、邊緣檢測等)、imageconvolution(自定義卷積矩陣)。

最佳實踐提醒

  1. **錯誤處理**:所有創建函數可能返回 false,需檢查並 die() 或拋出異常。
  2. **內存管理**:大圖處理及時 imagedestroy(),長運行腳本定期 gc_collect_cycles()。
  3. **字體路徑**:imagettftext 需絕對路徑 TTF 文件,建議配置常量 FONT_DIR。
  4. **輸出緩衝**:生成圖像前 ob_clean() 防止前序輸出污染二進制流。
  5. **安全**:用戶上傳圖像處理前驗證 MIME、尺寸、解壓炸彈(imagecreatefromstring 限制)。

GD 庫功能強大且零依賴,掌握基礎流程即可實現驗證碼、圖表、水印、縮略圖、海報合成等常見需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved