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

PHP GD 圖像處理完全指南:安裝配置、核心函數與實戰應用

     編輯:PHP 入門

PHP GD 圖像處理深度解析:從環境建置到動態圖片生成

GD 庫是 PHP 內建的圖形處理擴展,支援創建、編輯、輸出多種圖片格式 (JPEG、PNG、GIF、WebP、WBMP、XPM、BMP)。廣泛應用於驗證碼生成、圖片縮圖、水印添加、圖表繪製、頭像處理等場景。本文系統性介紹安裝配置、核心函數分類、常用操作模式與實戰範例。

環境安裝與驗證

PHP 配置啟用 GD

驗證安裝與支援格式

<?php
var_dump(gd_info());
/* 輸出範例:
array(12) {
  ["GD Version"]=> string(26) "bundled (2.1.0 compatible)"
  ["FreeType Support"]=> bool(true)
  ["GIF Read Support"]=> bool(true)
  ["GIF Create Support"]=> bool(true)
  ["JPEG Support"]=> bool(true)
  ["PNG Support"]=> bool(true)
  ["WBMP Support"]=> bool(true)
  ["XPM Support"]=> bool(false)
  ["XBM Support"]=> bool(true)
  ["WebP Support"]=> bool(true)
  ["BMP Support"]=> bool(true)
}
*/

核心函數分類速查

平台php.ini 設定
Windowsextension=gd (PHP 7.2+ 內建,舊版 extension=php_gd2.dll)
Linux (Debian/Ubuntu)apt-get install php-gd 並確認 extension=gd
Linux (RHEL/CentOS)yum install php-gd
macOS (Homebrew)brew install php (預設含 GD)
Dockerdocker-php-ext-install gd (官方映像)

實戰範例集

1. 產生驗證碼圖片

<?php
session_start();
$width = 120; $height = 40;
$image = imagecreatetruecolor($width, $height);

// 背景
$bg = imagecolorallocate($image, 230, 230, 230);
imagefilledrectangle($image, 0, 0, $width, $height, $bg);

// 雜訊線條
for ($i = 0; $i < 5; $i++) {
    $color = imagecolorallocate($image, rand(100,200), rand(100,200), rand(100,200));
    imageline($image, rand(0,$width), rand(0,$height), rand(0,$width), rand(0,$height), $color);
}

// 驗證碼文字
$code = '';
for ($i = 0; $i < 4; $i++) $code .= chr(rand(65,90)); // A-Z
$_SESSION['captcha'] = $code;

$fontSize = 5;
$x = 15;
foreach (str_split($code) as $char) {
    $color = imagecolorallocate($image, rand(0,100), rand(0,100), rand(0,100));
    imagestring($image, $fontSize, $x, 10, $char, $color);
    $x += 22;
}

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

2. 圖片縮圖 (保持比例、高品質)

function createThumbnail($srcPath, $destPath, $maxWidth, $maxHeight, $quality = 85) {
    list($srcW, $srcH, $type) = getimagesize($srcPath);
    if (!$srcW || !$srcH) return false;

    $ratio = min($maxWidth/$srcW, $maxHeight/$srcH);
    if ($ratio >= 1) return copy($srcPath, $destPath); // 無需縮小

    $dstW = (int)($srcW * $ratio);
    $dstH = (int)($srcH * $ratio);

    $srcImg = match($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($srcPath),
        IMAGETYPE_PNG => imagecreatefrompng($srcPath),
        IMAGETYPE_GIF => imagecreatefromgif($srcPath),
        IMAGETYPE_WEBP => imagecreatefromwebp($srcPath),
        default => null
    };
    if (!$srcImg) return false;

    $dstImg = imagecreatetruecolor($dstW, $dstH);
    // 保持透明度 (PNG/GIF)
    if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
        imagealphablending($dstImg, false);
        imagesavealpha($dstImg, true);
        $transparent = imagecolorallocatealpha($dstImg, 255, 255, 255, 127);
        imagefilledrectangle($dstImg, 0, 0, $dstW, $dstH, $transparent);
    }

    imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);

    $success = match($type) {
        IMAGETYPE_JPEG => imagejpeg($dstImg, $destPath, $quality),
        IMAGETYPE_PNG => imagepng($dstImg, $destPath, 9),
        IMAGETYPE_GIF => imagegif($dstImg, $destPath),
        IMAGETYPE_WEBP => imagewebp($dstImg, $destPath, $quality),
        default => false
    };

    imagedestroy($srcImg);
    imagedestroy($dstImg);
    return $success;
}

3. 添加文字水印

function addTextWatermark($srcPath, $destPath, $text, $fontFile, $fontSize = 20, $color = [255,255,255], $alpha = 50, $position = 'bottom-right', $margin = 10) {
    list($w, $h, $type) = getimagesize($srcPath);
    $src = imagecreatefromjpeg($srcPath); // 簡化:假設 JPEG

    $dst = imagecreatetruecolor($w, $h);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $w, $h);

    $textColor = imagecolorallocatealpha($dst, $color[0], $color[1], $color[2], $alpha);
    $box = imagettfbbox($fontSize, 0, $fontFile, $text);
    $textW = $box[2] - $box[0];
    $textH = $box[1] - $box[7];

    switch ($position) {
        case 'top-left': $x = $margin; $y = $margin + $textH; break;
        case 'top-right': $x = $w - $textW - $margin; $y = $margin + $textH; break;
        case 'bottom-left': $x = $margin; $y = $h - $margin; break;
        case 'bottom-right': $x = $w - $textW - $margin; $y = $h - $margin; break;
        case 'center': $x = ($w - $textW)/2; $y = ($h + $textH)/2; break;
    }

    imagettftext($dst, $fontSize, 0, $x, $y, $textColor, $fontFile, $text);
    imagejpeg($dst, $destPath, 90);
    imagedestroy($src); imagedestroy($dst);
}

4. 繪製簡單統計圖表 (長條圖)

function drawBarChart($data, $width = 600, $height = 400) {
    $img = imagecreatetruecolor($width, $height);
    $white = imagecolorallocate($img, 255, 255, 255);
    $gray = imagecolorallocate($img, 200, 200, 200);
    $blue = imagecolorallocate($img, 66, 133, 244);
    $dark = imagecolorallocate($img, 51, 51, 51);

    imagefilledrectangle($img, 0, 0, $width, $height, $white);

    $maxVal = max($data);
    $barCount = count($data);
    $barWidth = 40;
    $gap = ($width - $barCount * $barWidth) / ($barCount + 1);
    $scale = ($height - 80) / $maxVal;

    $x = $gap;
    foreach ($data as $label => $value) {
        $barH = (int)($value * $scale);
        $y = $height - 50 - $barH;
        imagefilledrectangle($img, $x, $y, $x + $barWidth, $height - 50, $blue);
        imagestring($img, 3, $x + 5, $height - 40, $label, $dark);
        imagestring($img, 3, $x + 5, $y - 20, $value, $dark);
        $x += $barWidth + $gap;
    }

    // 座標軸
    imageline($img, 30, 30, 30, $height - 50, $dark);
    imageline($img, 30, $height - 50, $width - 30, $height - 50, $dark);

    header('Content-Type: image/png');
    imagepng($img);
    imagedestroy($img);
}

// 使用
drawBarChart(['Jan'=>120, 'Feb'=>150, 'Mar'=>180, 'Apr'=>200]);

常見問題與最佳實務

分類代表函數
資訊獲取gd_info(), getimagesize(), getimagesizefromstring(), image_type_to_extension(), image_type_to_mime_type()
畫布建立imagecreatetruecolor(), imagecreate(), imagecreatefromjpeg/png/gif/webp/bmp/string()
輸出輸出imagejpeg/png/gif/webp/wbmp/bmp(), image2wbmp()
顏色管理imagecolorallocate(), imagecolorallocatealpha(), imagecolorat(), imagecolorclosest(), imagecolorclosestalpha(), imagecolorclosesthwb()
幾何繪製imagesetpixel(), imageline(), imagerectangle(), imagepolygon(), imageellipse(), imagearc(), imagefilledrectangle(), imagefilledpolygon(), imagefilledellipse(), imagefill(), imagefilltoborder()
文字繪製imagestring(), imagestringup(), imagettftext(), imagettfbbox(), imagechar(), imagecharup()
圖片複製合成imagecopy(), imagecopyresized(), imagecopyresampled(), imagecopymerge(), imagecopymergegray()
幾何變換imagerotate(), imageflip(), imagecrop(), imagecropauto(), imageaffine(), imageaffinematrixget(), imageaffinematrixconcat()
特效濾鏡imagefilter(), imageconvolution(), imageantialias(), imagealphablending(), imagesavealpha()
尺寸資訊imagesx(), imagesy()
資源釋放imagedestroy()

GD vs ImageMagick 選擇指南

問題解決方案
記憶體耗盡大圖處理前調大 memory_limit,處理完立即 imagedestroy()
透明背景變黑啟用 imagealphablending($img, false); imagesavealpha($img, true);
中文字體亂碼使用 imagettftext() 載入 .ttf 字體檔,確保檔案路徑正確
JPEG 品質/大小平衡imagejpeg($img, null, 75-85) 通常最佳
並發處理效能考慮 ImageMagick (imagick 擴展) 或外部服務

總結

GD 庫是 PHP 內建圖形處理的基石,掌握畫布建立、顏色管理、幾何繪製、文字渲染、圖片合成、輸出輸出等核心流程,即可實現驗證碼、縮圖、水印、圖表等常見需求。對於高階圖像處理,建議評估 ImageMagick 或雲端圖片處理服務 (Imgix, Cloudinary, AWS Lambda@Edge)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
維度GDImageMagick
功能豐富度基礎繪圖、文字、縮放200+ 格式、進階特效、向量圖、色彩管理
效能簡單操作較快複雜操作優化更好
記憶體管理PHP 進程內外部進程/共享記憶體
部署複雜度PHP 內建,零依賴需安裝 ImageMagick + imagick 擴展
適用場景驗證碼、縮圖、簡單水印、圖表專業圖片處理、批次轉檔、色彩校正、PDF/向量