萬盛學電腦網

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

PHP GD 圖像處理完全指南:從創建、縮放、裁剪到水印、旋轉、銳化

PHP GD 庫圖像處理核心函數速查與實戰封裝

GD 庫是 PHP 內建的圖像處理擴展,支援 JPEG、PNG、GIF、WebP 等格式。本文系統梳理常用函數,並提供可直接用於生產的封裝函數庫。

一、圖像資源創建與輸出

<?php
// 1. 創建真彩色畫布
$img = imagecreatetruecolor(800, 600);

// 2. 從文件加載(自動識別格式)
$img = imagecreatefromjpeg('photo.jpg');
$img = imagecreatefrompng('logo.png');
$img = imagecreatefromgif('anim.gif');
$img = imagecreatefromwebp('image.webp'); // PHP 5.5+

// 3. 輸出到瀏覽器或文件
header('Content-Type: image/jpeg');
imagejpeg($img, null, 90); // 品質 90

// 保存文件
imagepng($img, 'output.png', 6); // 壓縮級別 0-9
imagegif($img, 'output.gif');
imagewebp($img, 'output.webp', 80); // 品質 0-100

// 4. 釋放資源(必須調用)
imagedestroy($img);
?>

二、獲取圖像屬性

<?php
// 方法 1:GD 內部函數
$width  = imagesx($img);
$height = imagesy($img);

// 方法 2:getimagesize() 不需加載圖像,效率更高
$info = getimagesize('photo.jpg');
// $info[0] 寬度, $info[1] 高度, $info[2] 類型常量, $info[3] 'width="..." height="..."'
$mime = $info['mime']; // image/jpeg 等
?>

三、透明度處理(關鍵:GIF/PNG 透明保持)

<?php
function preserveTransparency($srcImg, $dstImg) {
    if (($transparentIndex = imagecolortransparent($srcImg)) >= 0) {
        // GIF: 索引顏色透明
        $colors = imagecolorsforindex($srcImg, $transparentIndex);
        $newTransparent = imagecolorallocatealpha($dstImg, $colors['red'], $colors['green'], $colors['blue'], 127);
        imagefill($dstImg, 0, 0, $newTransparent);
        imagecolortransparent($dstImg, $newTransparent);
    } elseif (imageistruecolor($srcImg)) {
        // PNG: Alpha 通道透明
        imagealphablending($dstImg, false);
        $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
        imagefill($dstImg, 0, 0, $transparent);
        imagesavealpha($dstImg, true);
    }
}
?>

四、縮放與裁剪核心函數對比

函數特點適用場景
imagecopyresized()簡單像素複製,速度快,質量一般縮略圖、預覽圖、質量要求不高
imagecopyresampled()重採樣插值,質量高,速度稍慢產品圖、頭像、高質量縮放

五、等比例縮放通用函數(支援透明保持)

<?php
/**
 * 等比例縮放圖像
 *
 * @param string $srcPath 源文件路徑
 * @param int $maxWidth 最大寬度
 * @param int $maxHeight 最大高度
 * @param string $dstPath 目標路徑
 * @param int $quality JPEG/WebP 品質 (0-100)
 * @return bool
 */
function smartResize($srcPath, $maxWidth, $maxHeight, $dstPath, $quality = 90) {
    list($srcW, $srcH, $type) = getimagesize($srcPath);
    if (!$srcW || !$srcH) return false;

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

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

    // 加載源圖像
    $createFunc = [
        IMAGETYPE_GIF  => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG  => 'imagecreatefrompng',
        IMAGETYPE_WEBP => 'imagecreatefromwebp',
    ];
    if (!isset($createFunc[$type])) return false;
    $srcImg = $createFunc[$type]($srcPath);

    // 保持透明度
    preserveTransparency($srcImg, $dstImg);

    // 高質量重採樣
    imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);

    // 輸出
    $outputFunc = [
        IMAGETYPE_GIF  => fn() => imagegif($dstImg, $dstPath),
        IMAGETYPE_JPEG => fn() => imagejpeg($dstImg, $dstPath, $quality),
        IMAGETYPE_PNG  => fn() => imagepng($dstImg, $dstPath, 6),
        IMAGETYPE_WEBP => fn() => imagewebp($dstImg, $dstPath, $quality),
    ];
    $result = $outputFunc[$type]();

    imagedestroy($srcImg);
    imagedestroy($dstImg);
    return $result;
}
?>

六、圖片裁剪(切圖)

<?php
/**
 * 圖片裁剪
 *
 * @param string $srcPath 源文件
 * @param int $x 起始 X
 * @param int $y 起始 Y
 * @param int $w 裁剪寬度
 * @param int $h 裁剪高度
 * @param string $dstPath 目標文件
 */
function cropImage($srcPath, $x, $y, $w, $h, $dstPath) {
    list($srcW, $srcH, $type) = getimagesize($srcPath);
    $createFunc = [1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng', 15=>'imagecreatefromwbmp'];
    $srcImg = $createFunc[$type]($srcPath);

    $dstImg = imagecreatetruecolor($w, $h);
    preserveTransparency($srcImg, $dstImg);
    imagecopyresampled($dstImg, $srcImg, 0, 0, $x, $y, $w, $h, $w, $h);

    $outputFunc = [1=>'imagegif', 2=>'imagejpeg', 3=>'imagepng', 15=>'imagewbmp'];
    $outputFunc[$type]($dstImg, $dstPath);

    imagedestroy($srcImg);
    imagedestroy($dstImg);
}
?>

七、水印添加(文字 + 圖片)

<?php
/**
 * 添加文字水印
 */
function addTextWatermark($srcPath, $text, $fontFile, $fontSize = 20, $color = [255,255,255], $x = 10, $y = 10, $dstPath = null) {
    $dstPath = $dstPath ?: $srcPath;
    list(,,$type) = getimagesize($srcPath);
    $createFunc = [1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng'];
    $img = $createFunc[$type]($srcPath);

    $colorAllocated = imagecolorallocate($img, ...$color);
    imagettftext($img, $fontSize, 0, $x, $y, $colorAllocated, $fontFile, $text);

    $outputFunc = [1=>'imagegif', 2=>'imagejpeg', 3=>'imagepng'];
    $outputFunc[$type]($img, $dstPath);
    imagedestroy($img);
}

/**
 * 添加圖片水印(支援 PNG 透明)
 */
function addImageWatermark($srcPath, $watermarkPath, $x, $y, $dstPath = null, $opacity = 100) {
    $dstPath = $dstPath ?: $srcPath;
    list(,,$type) = getimagesize($srcPath);
    $createFunc = [1=>'imagecreatefromgif', 2=>'imagecreatefromjpeg', 3=>'imagecreatefrompng'];
    $img = $createFunc[$type]($srcPath);

    $wm = imagecreatefrompng($watermarkPath); // 水印建議用 PNG
    $wmW = imagesx($wm);
    $wmH = imagesy($wm);

    // 處理透明度
    if ($opacity < 100) {
        imagefilter($wm, IMG_FILTER_COLORIZE, 0, 0, 0, 127 * (100 - $opacity) / 100);
    }

    imagecopy($img, $wm, $x, $y, 0, 0, $wmW, $wmH);
    $outputFunc = [1=>'imagegif', 2=>'imagejpeg', 3=>'imagepng'];
    $outputFunc[$type]($img, $dstPath);

    imagedestroy($img);
    imagedestroy($wm);
}
?>

八、旋轉與翻轉

<?php
// 旋轉(角度順時針,背景色用 0 表示透明)
$rotated = imagerotate($img, 45, 0); // 45 度
imagepng($rotated, 'rotated.png');
imagedestroy($rotated);

// 水平翻轉(鏡像)
function flipHorizontal($srcPath, $dstPath) {
    $img = imagecreatefromjpeg($srcPath);
    $w = imagesx($img); $h = imagesy($img);
    $dst = imagecreatetruecolor($w, $h);
    for ($x = 0; $x < $w; $x++) {
        imagecopy($dst, $img, $w - $x - 1, 0, $x, 0, 1, $h);
    }
    imagejpeg($dst, $dstPath);
    imagedestroy($img); imagedestroy($dst);
}

// 垂直翻轉
function flipVertical($srcPath, $dstPath) {
    $img = imagecreatefromjpeg($srcPath);
    $w = imagesx($img); $h = imagesy($img);
    $dst = imagecreatetruecolor($w, $h);
    for ($y = 0; $y < $h; $y++) {
        imagecopy($dst, $img, 0, $h - $y - 1, 0, $y, $w, 1);
    }
    imagejpeg($dst, $dstPath);
    imagedestroy($img); imagedestroy($dst);
}
?>

九、銳化濾鏡(PHP 5.5+)

<?php
// 簡單銳化
imageconvolution($img, [
    [-1, -1, -1],
    [-1, 16, -1],
    [-1, -1, -1]
], 8, 0);

// 或使用內建濾鏡(需 GD 綁定 libgd)
imagefilter($img, IMG_FILTER_CONTRAST, 10); // 增加對比度
imagefilter($img, IMG_FILTER_GAUSSIAN_BLUR); // 高斯模糊(反銳化掩膜基礎)
?>

十、完整實戰示例:生成帶水印的商品縮略圖

<?php
// 原圖路徑
$source = 'uploads/product_original.jpg';
// 目標縮略圖
$thumb = 'uploads/thumb_product_300x300.jpg';
// 水印文件
$watermark = 'assets/watermark.png';

// 1. 等比縮放至 300x300 內
smartResize($source, 300, 300, $thumb, 85);

// 2. 添加右下角圖片水印(距邊緣 10px)
list($tw, $th) = getimagesize($watermark);
list($iw, $ih) = getimagesize($thumb);
addImageWatermark($thumb, $watermark, $iw - $tw - 10, $ih - $th - 10, $thumb, 50);

echo "縮略圖生成完成: $thumb";
?>

性能優化提示

  • 大量圖片處理請使用 imagemagick (Imagick 擴展),速度更快、格式支援更全。
  • 生產環境建議異步處理(消息隊列 + Worker),避免阻塞 Web 進程。
  • 及時 imagedestroy() 釋放內存,防止內存洩漏導致 PHP-FPM 重啟。
  • 開啟 OPcache 並調整 memory_limit 適應大圖處理。
copyright © 萬盛學電腦網 all rights reserved