萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 圖片處理完整教學:建立、縮圖、繪文字、水印、格式轉換

前言

GD 是 PHP 內建圖形處理擴充,支援建立圖片、縮圖、繪圖、加浮水印、格式轉換等。本文完整示範常見操作,並說明記憶體管理、錯誤處理與現代替代方案。

環境檢查

<?php
if (!extension_loaded('gd')) {
    die('GD 擴充未安裝。Ubuntu: apt-get install php-gd');
}
$info = gd_info();
echo "GD 版本: {$info['GD Version']}<br>";
echo "支援格式: " . implode(', ', [
    $info['GIF Read Support']  ? 'GIF' : '',
    $info['JPEG Support']      ? 'JPEG' : '',
    $info['PNG Support']       ? 'PNG' : '',
    $info['WebP Support']      ? 'WebP' : '',
]) . "<br>";
?>

1. 建立純色背景圖並輸出文字

<?php
$width  = 400;
$height = 200;

// 建立真彩色圖片資源
$im = imagecreatetruecolor($width, $height);

// 分配顏色 (R, G, B)
$white = imagecolorallocate($im, 255, 255, 255);
$blue  = imagecolorallocate($im, 0, 51, 102);
$gray  = imagecolorallocate($im, 200, 200, 200);

// 填滿背景
imagefill($im, 0, 0, $blue);

// 繪製矩形邊框
imagerectangle($im, 0, 0, $width-1, $height-1, $white);

// 繪製文字 (需 FreeType 支援才能用 TTF 字型)
$fontSize = 5;
$text     = 'Hello, PHP GD!';
$textBox  = imagettfbbox($fontSize, 0, __DIR__ . '/fonts/DejaVuSans.ttf', $text);
$textW    = $textBox[2] - $textBox[0];
$textH    = $textBox[1] - $textBox[7];
$x = ($width - $textW) / 2;
$y = ($height + $textH) / 2;

// 使用內建字體 (無需 TTF)
imagestring($im, 5, 50, 80, $text, $white);

// 輸出圖片
header('Content-Type: image/png');
imagepng($im);

// 釋放記憶體
imagedestroy($im);
?>

2. 產生縮圖 (保持比例)

<?php
function createThumbnail($srcPath, $destPath, $maxW = 300, $maxH = 300, $quality = 85) {
    // 取得原圖資訊
    $info = getimagesize($srcPath);
    if (!$info) return false;
    [$srcW, $srcH, $type] = $info;

    // 計算縮放比例
    $ratio = min($maxW / $srcW, $maxH / $srcH);
    if ($ratio >= 1) return false; // 無需縮小

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

    // 依類型建立來源圖片資源
    switch ($type) {
        case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($srcPath); break;
        case IMAGETYPE_PNG:  $src = imagecreatefrompng($srcPath);  break;
        case IMAGETYPE_GIF:  $src = imagecreatefromgif($srcPath);  break;
        case IMAGETYPE_WEBP: $src = imagecreatefromwebp($srcPath); break;
        default: return false;
    }

    // 建立目標真彩色圖片
    $dst = imagecreatetruecolor($dstW, $dstH);

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

    // 重採樣縮放 (品質優於 imagecopyresized)
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);

    // 輸出
    $result = false;
    switch ($type) {
        case IMAGETYPE_JPEG: $result = imagejpeg($dst, $destPath, $quality); break;
        case IMAGETYPE_PNG:  $result = imagepng($dst, $destPath); break;
        case IMAGETYPE_GIF:  $result = imagegif($dst, $destPath); break;
        case IMAGETYPE_WEBP: $result = imagewebp($dst, $destPath, $quality); break;
    }

    imagedestroy($src);
    imagedestroy($dst);
    return $result;
}

// 使用
createThumbnail('photo.jpg', 'thumb_photo.jpg', 300, 200);
?>

3. 給圖片加浮水印 (文字/圖片)

<?php
function addWatermark($srcPath, $destPath, $waterText = '© MySite', $fontSize = 20, $opacity = 50) {
    $info = getimagesize($srcPath);
    if (!$info) return false;
    [$w, $h, $type] = $info;

    // 載入原圖
    $src = match($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($srcPath),
        IMAGETYPE_PNG  => imagecreatefrompng($srcPath),
        IMAGETYPE_GIF  => imagecreatefromgif($srcPath),
        default => null,
    };
    if (!$src) return false;

    // 建立水印圖層 (透明背景)
    $watermark = imagecreatetruecolor($w, $h);
    imagealphablending($watermark, false);
    $transparent = imagecolorallocatealpha($watermark, 0, 0, 0, 127);
    imagefill($watermark, 0, 0, $transparent);
    imagesavealpha($watermark, true);

    // 繪製水印文字 (右下角)
    $color = imagecolorallocatealpha($watermark, 255, 255, 255, $opacity);
    $font = __DIR__ . '/fonts/DejaVuSans.ttf';
    $box = imagettfbbox($fontSize, 0, $font, $waterText);
    $tw = $box[2] - $box[0];
    $th = $box[1] - $box[7];
    $tx = $w - $tw - 20;
    $ty = $h - $th - 20;
    imagettftext($watermark, $fontSize, 0, $tx, $ty, $color, $font, $waterText);

    // 合併圖層
    imagecopy($src, $watermark, 0, 0, 0, 0, $w, $h);

    // 輸出
    $result = match($type) {
        IMAGETYPE_JPEG => imagejpeg($src, $destPath, 90),
        IMAGETYPE_PNG  => imagepng($src, $destPath),
        IMAGETYPE_GIF  => imagegif($src, $destPath),
        default => false,
    };

    imagedestroy($src);
    imagedestroy($watermark);
    return $result;
}
?>

4. 取得圖片資訊

<?php
$info = getimagesize('photo.jpg');
/*
回傳陣列:
[0] => 寬度
[1] => 高度
[2] => 類型常數 (IMAGETYPE_JPEG=2 等)
[3] => 完整 width/height 字串
['bits'] => 色深
['channels'] => 通道數 (3=RGB, 4=RGBA)
['mime'] => MIME 類型
*/
echo "寬: {$info[0]}, 高: {$info[1]}, MIME: {$info['mime']}";
?>

5. 格式轉換:PNG 轉 JPEG (去透明背景)

<?php
function pngToJpeg($srcPath, $destPath, $bgColor = [255,255,255], $quality = 90) {
    $src = imagecreatefrompng($srcPath);
    $w = imagesx($src);
    $h = imagesy($src);

    $dst = imagecreatetruecolor($w, $h);
    $bg = imagecolorallocate($dst, ...$bgColor);
    imagefill($dst, 0, 0, $bg);
    imagecopy($dst, $src, 0, 0, 0, 0, $w, $h);

    $result = imagejpeg($dst, $destPath, $quality);
    imagedestroy($src);
    imagedestroy($dst);
    return $result;
}
?>

記憶體管理關鍵

  • 每個 imagecreate* 都必須配對 imagedestroy()
  • 大圖處理時調整 memory_limit (如 256M)
  • 批次處理建議分批、及時釋放、考慮 CLI 模式執行

現代替代方案

方案優點適用場景
Intervention Image鏈式語法、Laravel 整合、支援 ImageMagick現代框架專案
ImageMagick (imagick)功能強大、格式支援多、效能佳高併發、複雜處理
Spatie Image Optimizer自動最佳化壓縮部署流程整合
GD零依賴、內建、簡單操作足夠輕量專案、基礎縮圖/水印
copyright © 萬盛學電腦網 all rights reserved