萬盛學電腦網

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

PHP 圖像操作完全指南:3D 圖表、縮放、旋轉、裁剪與浮水印

前言

在現代 Web 開發中,圖片處理幾乎是不可或缺的功能。無論是生成統計圖表、調整上傳圖片尺寸、添加版權浮水印,還是實現圖片旋轉裁剪,PHP 的 GD 庫都提供了強大且靈活的解決方案。本教程將系統講解如何使用 PHP GD 庫完成 3D 扇形圖繪製、圖片縮放、旋轉、裁剪以及添加浮水印等核心操作。

一、繪製 3D 扇形統計圖

利用 imagefilledarc() 函數配合循環疊加,可以輕松創建具有立體效果的 3D 扇形圖。以下是完整代碼範例:

<?php
header("Content-type: text/html; charset=utf-8");

// 建立畫布
$image = imagecreatetruecolor(400, 300);

// 定義顏色
$white      = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray       = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray   = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy       = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy   = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red        = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred    = imagecolorallocate($image, 0x90, 0x00, 0x00);

// 填充背景
imagefill($image, 0, 0, $white);

// 繪製 3D 效果:由下往上疊加多層扇形
for ($i = 60; $i > 50; $i--) {
    imagefilledarc($image, 200, $i, 200, 100, -160, 40, $darknavy, IMG_ARC_PIE);
    imagefilledarc($image, 200, $i, 200, 100, 40, 75, $darkgray, IMG_ARC_PIE);
    imagefilledarc($image, 200, $i, 200, 100, 75, 200, $darkred, IMG_ARC_PIE);
}

// 繪製頂層扇形(實際數據層)
imagefilledarc($image, 200, 50, 200, 100, -160, 40, $navy, IMG_ARC_PIE);
imagefilledarc($image, 200, 50, 200, 100, 40, 75, $gray, IMG_ARC_PIE);
imagefilledarc($image, 200, 50, 200, 100, 75, 200, $red, IMG_ARC_PIE);

// 添加標籤文字
imagestring($image, 5, 150, 120, "30%", $white);
imagestring($image, 5, 250, 80, "60%", $white);
imagestring($image, 5, 280, 150, "10%", $white);

// 輸出圖片
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

關鍵點: 通過將同一扇形在不同 Y 座標重複繪製(從底部向上),形成厚度感;頂層使用較亮顏色,側面使用深色系,即可產生 3D 視覺效果。

二、圖片縮放

使用 imagecopyresampled() 可實現高質量的圖片縮放,保持清晰度。以下函數支援按比例縮放、指定最大寬高、以及針對不同圖片格式(JPEG、PNG、GIF)的處理:

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

    // 計算目標尺寸
    $ratio = min($maxWidth / $srcW, $maxHeight / $srcH);
    if ($ratio >= 1) { // 原圖較小,無需縮放
        copy($srcPath, $dstPath);
        return true;
    }
    $dstW = (int)($srcW * $ratio);
    $dstH = (int)($srcH * $ratio);

    // 建立目標畫布
    $dstImg = imagecreatetruecolor($dstW, $dstH);

    // 根據類型建立源圖片資源
    switch ($type) {
        case IMAGETYPE_JPEG:  $srcImg = imagecreatefromjpeg($srcPath);  break;
        case IMAGETYPE_PNG:   $srcImg = imagecreatefrompng($srcPath);   break;
        case IMAGETYPE_GIF:   $srcImg = imagecreatefromgif($srcPath);   break;
        default: return false;
    }

    // 保持透明度(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);

    // 輸出
    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($dstImg, $dstPath, $quality); break;
        case IMAGETYPE_PNG:  imagepng($dstImg, $dstPath); break;
        case IMAGETYPE_GIF:  imagegif($dstImg, $dstPath); break;
    }
    imagedestroy($srcImg);
    imagedestroy($dstImg);
    return true;
}

三、圖片旋轉

imagerotate() 函數可將圖片按指定角度旋轉,並可設定背景填充色:

function rotateImage($srcPath, $dstPath, $angle, $bgColor = 0xFFFFFF) {
    list($w, $h, $type) = getimagesize($srcPath);
    $srcImg = ($type == IMAGETYPE_JPEG) ? imagecreatefromjpeg($srcPath) :
              ($type == IMAGETYPE_PNG) ? imagecreatefrompng($srcPath) :
              ($type == IMAGETYPE_GIF) ? imagecreatefromgif($srcPath) : null;
    if (!$srcImg) return false;

    $rotated = imagerotate($srcImg, $angle, $bgColor);
    // 保持透明度
    if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
        imagealphablending($rotated, false);
        imagesavealpha($rotated, true);
    }

    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($rotated, $dstPath, 90); break;
        case IMAGETYPE_PNG:  imagepng($rotated, $dstPath); break;
        case IMAGETYPE_GIF:  imagegif($rotated, $dstPath); break;
    }
    imagedestroy($srcImg);
    imagedestroy($rotated);
    return true;
}

四、圖片裁剪

裁剪可使用 imagecrop() (PHP 5.5+) 或手動 imagecopy() 實現任意區域截取:

function cropImage($srcPath, $dstPath, $x, $y, $width, $height) {
    list($w, $h, $type) = getimagesize($srcPath);
    $srcImg = ($type == IMAGETYPE_JPEG) ? imagecreatefromjpeg($srcPath) :
              ($type == IMAGETYPE_PNG) ? imagecreatefrompng($srcPath) :
              ($type == IMAGETYPE_GIF) ? imagecreatefromgif($srcPath) : null;
    if (!$srcImg) return false;

    // 邊界檢查
    $x = max(0, min($x, $w - 1));
    $y = max(0, min($y, $h - 1));
    $width  = min($width, $w - $x);
    $height = min($height, $h - $y);

    $dstImg = imagecreatetruecolor($width, $height);
    // 透明度處理
    if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
        imagealphablending($dstImg, false);
        imagesavealpha($dstImg, true);
    }
    imagecopy($dstImg, $srcImg, 0, 0, $x, $y, $width, $height);

    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($dstImg, $dstPath, 90); break;
        case IMAGETYPE_PNG:  imagepng($dstImg, $dstPath); break;
        case IMAGETYPE_GIF:  imagegif($dstImg, $dstPath); break;
    }
    imagedestroy($srcImg);
    imagedestroy($dstImg);
    return true;
}

五、添加浮水印(文字 / 圖片)

浮水印可保護版權,分為文字浮水印與圖片浮水印兩種:

1. 文字浮水印

function addTextWatermark($srcPath, $dstPath, $text, $fontSize = 20, $color = 0xFF0000, $position = 'bottom-right', $margin = 10, $fontFile = null) {
    list($w, $h, $type) = getimagesize($srcPath);
    $srcImg = ($type == IMAGETYPE_JPEG) ? imagecreatefromjpeg($srcPath) :
              ($type == IMAGETYPE_PNG) ? imagecreatefrompng($srcPath) :
              ($type == IMAGETYPE_GIF) ? imagecreatefromgif($srcPath) : null;
    if (!$srcImg) return false;

    $textColor = imagecolorallocate($srcImg, ($color>>16)&0xFF, ($color>>8)&0xFF, $color&0xFF);
    // 計算文字邊界框
    $box = $fontFile ? imagettfbbox($fontSize, 0, $fontFile, $text) : imagefontbbox($fontSize, 0, 0, $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 'center':        $x = ($w - $textW)/2; $y = ($h + $textH)/2; break;
        default:              $x = $w - $textW - $margin; $y = $h - $margin; // bottom-right
    }

    if ($fontFile) {
        imagettftext($srcImg, $fontSize, 0, $x, $y, $textColor, $fontFile, $text);
    } else {
        imagestring($srcImg, $fontSize, $x, $y - $textH, $text, $textColor);
    }

    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($srcImg, $dstPath, 90); break;
        case IMAGETYPE_PNG:  imagepng($srcImg, $dstPath); break;
        case IMAGETYPE_GIF:  imagegif($srcImg, $dstPath); break;
    }
    imagedestroy($srcImg);
    return true;
}

2. 圖片浮水印(支援透明 PNG)

function addImageWatermark($srcPath, $dstPath, $waterPath, $position = 'bottom-right', $margin = 10, $opacity = 50) {
    list($w, $h, $type) = getimagesize($srcPath);
    list($ww, $wh, $wtype) = getimagesize($waterPath);
    if ($ww > $w || $wh > $h) return false; // 水印不可大於原圖

    $srcImg = ($type == IMAGETYPE_JPEG) ? imagecreatefromjpeg($srcPath) :
              ($type == IMAGETYPE_PNG) ? imagecreatefrompng($srcPath) :
              ($type == IMAGETYPE_GIF) ? imagecreatefromgif($srcPath) : null;
    $waterImg = ($wtype == IMAGETYPE_JPEG) ? imagecreatefromjpeg($waterPath) :
                ($wtype == IMAGETYPE_PNG) ? imagecreatefrompng($waterPath) :
                ($wtype == IMAGETYPE_GIF) ? imagecreatefromgif($waterPath) : null;
    if (!$srcImg || !$waterImg) return false;

    // 位置計算
    switch ($position) {
        case 'top-left':      $x = $margin; $y = $margin; break;
        case 'top-right':     $x = $w - $ww - $margin; $y = $margin; break;
        case 'bottom-left':   $x = $margin; $y = $h - $wh - $margin; break;
        case 'center':        $x = ($w - $ww)/2; $y = ($h - $wh)/2; break;
        default:              $x = $w - $ww - $margin; $y = $h - $wh - $margin;
    }

    // 設定透明度並合併
    imagecopymerge($srcImg, $waterImg, $x, $y, 0, 0, $ww, $wh, $opacity);

    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($srcImg, $dstPath, 90); break;
        case IMAGETYPE_PNG:  imagepng($srcImg, $dstPath); break;
        case IMAGETYPE_GIF:  imagegif($srcImg, $dstPath); break;
    }
    imagedestroy($srcImg);
    imagedestroy($waterImg);
    return true;
}

最佳實踐建議

  • 記憶體管理: 處理大圖時,及時調用 imagedestroy() 釋放資源;必要時調大 memory_limit。
  • 錯誤處理: 每個 GD 函數調用前檢查資源是否有效,捕獲 gd 相關錯誤。
  • 安全性: 上傳圖片務必驗證 MIME 類型、檔案副檔名,並重新命名儲存,防止腳本注入。
  • 效能優化: 對頻繁存取的圖片操作結果進行快取(如儲存縮圖),避免重複運算。
  • 替代方案: 對於極高效能或複雜向量圖形需求,可考慮 ImageMagick (imagick 擴展) 或介面調用外部工具。

結語

掌握 PHP GD 庫的核心函數,即可應對絕大多數 Web 圖片處理場景。從動態生成統計圖表、自動產生縮圖、批次加浮水印,到使用者頭像裁剪旋轉,這些技能將大幅提升專案的使用者體驗與開發效率。建議在實際專案中封裝成可複用的工具類,並結合快取策略,讓圖片處理既優雅又高效。

copyright © 萬盛學電腦網 all rights reserved