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

PHP GD 圖像處理:imagecreatetruecolor 建立真彩色、透明背景與高清輸出完全指南

     編輯:PHP 綜合知識

前言:為什麼用 True Color?

imagecreatetruecolor() 建立 24-bit 真彩色圖像(每像素 1677 萬色),支援 Alpha 通道透明度,是現代 PHP GD 圖像處理的基石。舊式 imagecreate() 僅支援 256 色調色盤,已不建議使用。

核心函數速查

函數用途關鍵參數
imagecreatetruecolor(w, h)建立真彩色畫布寬、高(像素)
imagecolorallocatealpha(img, r, g, b, alpha)配置含透明度的顏色alpha: 0(不透明)~127(全透明)
imagesavealpha(img, true)啟用 Alpha 通道儲存(PNG 必須)布林值
imagefill(img, x, y, color)填充區域(常用填滿背景)起始座標、顏色
imagepng(img, file, quality)輸出 PNG(無損、支援透明)quality 0-9(壓縮等級)
imagedestroy(img)釋放記憶體資源 handle

範例 1:最簡單的真彩色文字圖片

<?php
header('Content-Type: image/png');

$im = imagecreatetruecolor(200, 80) or die('GD 初始化失敗');
$bg   = imagecolorallocate($im, 30, 30, 40);      // 深灰藍背景
$text = imagecolorallocate($im, 255, 255, 255);   // 白字
imagefill($im, 0, 0, $bg);
imagestring($im, 5, 20, 25, 'Hello GD!', $text);
imagepng($im);
imagedestroy($im);

範例 2:透明背景 + 半透明圓形疊加

<?php
header('Content-Type: image/png');

$size = 300;
$im = imagecreatetruecolor($size, $size);

// 關鍵:啟用 Alpha 儲存
imagesavealpha($im, true);

// 完全透明背景
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparent);

// 半透明顏色(alpha=75 約 41% 不透明)
$red   = imagecolorallocatealpha($im, 255, 0, 0, 75);
$green = imagecolorallocatealpha($im, 0, 255, 0, 75);
$blue  = imagecolorallocatealpha($im, 0, 0, 255, 75);

// 繪製三個重疊圓
imagefilledellipse($im, 100, 75, 150, 150, $red);
imagefilledellipse($im, 120, 165, 150, 150, $green);
imagefilledellipse($im, 187, 125, 150, 150, $blue);

imagepng($im);
imagedestroy($im);

範例 3:動態文字水印(含陰影、自訂字體)

<?php
header('Content-Type: image/png');

$text = $_GET['text'] ?? 'Watermark';
$font = __DIR__ . '/fonts/NotoSansTC-Regular.otf'; // 需自備 TTF/OTF

$im = imagecreatetruecolor(400, 80);
imagesavealpha($im, true);
$trans = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans);

$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// 陰影(偏移 1px)
imagettftext($im, 24, 0, 11, 41, $black, $font, $text);
// 主文字
imagettftext($im, 24, 0, 10, 40, $white, $font, $text);

imagepng($im);
imagedestroy($im);

範例 4:高清縮圖(等比例、保持透明)

function createThumbnail(string $srcPath, string $dstPath, int $maxW, int $maxH, int $quality = 90): bool
{
    $info = getimagesize($srcPath);
    if (!$info) return false;
    [$srcW, $srcH, $type] = $info;

    // 計算目標尺寸(等比例縮放)
    $ratio = min($maxW / $srcW, $maxH / $srcH);
    if ($ratio >= 1) { // 無需放大
        return copy($srcPath, $dstPath);
    }
    $dstW = (int)round($srcW * $ratio);
    $dstH = (int)round($srcH * $ratio);

    // 載入來源
    $createFrom = match ($type) {
        IMAGETYPE_GIF  => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG  => 'imagecreatefrompng',
        IMAGETYPE_WEBP => 'imagecreatefromwebp',
        default        => null,
    };
    if (!$createFrom) return false;
    $src = $createFrom($srcPath);

    // 建立真彩色目標
    $dst = imagecreatetruecolor($dstW, $dstH);
    // 保持透明
    if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF || $type === IMAGETYPE_WEBP) {
        imagesavealpha($dst, true);
        $trans = imagecolorallocatealpha($dst, 0, 0, 0, 127);
        imagefill($dst, 0, 0, $trans);
    }

    // 高品質重採樣
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);

    // 輸出
    $result = match ($type) {
        IMAGETYPE_GIF  => imagegif($dst, $dstPath),
        IMAGETYPE_JPEG => imagejpeg($dst, $dstPath, $quality),
        IMAGETYPE_PNG  => imagepng($dst, $dstPath, 9), // PNG 壓縮等級 0-9
        IMAGETYPE_WEBP => imagewebp($dst, $dstPath, $quality),
        default        => false,
    };

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

常見坑與解決方案

  1. 輸出前未送 Header:必須在任何輸出前呼叫 header('Content-Type: image/png'),否則瀏覽器會顯示亂碼。
  2. PNG 透明失效:缺少 imagesavealpha($im, true) 或未用 imagecolorallocatealpha 建立透明色。
  3. JPEG 不支援透明:需輸出 PNG/WebP/AVIF 才能保留透明背景。
  4. 字體路徑錯誤:imagettftext 需絕對路徑,建議用 __DIR__ 定位。
  5. 記憶體耗盡:大圖處理前調整 memory_limit,處理完立即 imagedestroy()。
  6. GD 未啟用 FreeType:編譯 PHP 時需 --with-freetype,否則 imagettftext 失效。

效能優化建議

  • 重複使用的畫布(如水印 Logo)預先載入並快取資源,避免每請求重讀檔案。
  • 大量圖片處理改用 CLI 排程 + 隊列,避免阻塞 Web 請求。
  • 考慮改用 ImageMagick (Imagick 擴展):功能更豐富、速度更快、支援更多格式(HEIC、AVIF、PDF 等)。
  • 輸出 WebP 可大幅減小檔案體積(需 GD 2.3.0+ 或 Imagick)。

總結

imagecreatetruecolor 搭配 imagesavealpha、imagecolorallocatealpha 是 PHP GD 處理真彩色與透明度的標準組合。掌握建立畫布、配置顏色、繪製圖形/文字、高品質重採樣、正確輸出 Header 與釋放資源六大步驟,即能應對驗證碼、水印、縮圖、圖表等大多數圖像動態生成需求。

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