萬盛學電腦網

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

PHP GD 生成圓角圖片:四角獨立控制、背景色填充、多格式輸出完整實現

利用 GD 繪製圓角矩形遮罩,將原圖合成到圓角畫布上,實現任意半徑、四角可選的圓角圖片生成。本文提供完整的 rounded_image() 函數,支援 JPEG/PNG/GIF/WebP 輸入輸出、十六進制背景色、抗鋸齒平滑邊緣。

核心函數

function rounded_image(
    string $src,
    string $dest,
    int $radius = 20,
    array $corners = ['tl'=>true, 'tr'=>true, 'br'=>true, 'bl'=>true],
    string $bgColor = 'FFFFFF',
    int $quality = 90
): bool {
    // 1. 載入源圖
    $info = @getimagesize($src);
    if (!$info) throw new InvalidArgumentException("無效圖片: $src");
    [$w, $h, $type] = $info;
    $createFrom = match ($type) {
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG  => 'imagecreatefrompng',
        IMAGETYPE_GIF  => 'imagecreatefromgif',
        IMAGETYPE_WEBP => 'imagecreatefromwebp',
        default => throw new RuntimeException("不支援格式: $type"),
    };
    $srcImg = $createFrom($src);
    if (!$srcImg) throw new RuntimeException("GD 解碼失敗: $src");

    // 2. 創建 2x 放大畫布(超採樣抗鋸齒)
    $scale = 2;
    $bigW = $w * $scale; $bigH = $h * $scale;
    $bigRadius = $radius * $scale;
    $big = imagecreatetruecolor($bigW, $bigH);

    // 3. 解析背景色
    $bg = sscanf($bgColor, "%2x%2x%2x");
    $bgColorAlloc = imagecolorallocatealpha($big, $bg[0], $bg[1], $bg[2], 0);

    // 4. 繪製圓角矩形遮罩(白色前景,背景透明)
    $fg = imagecolorallocatealpha($big, 255, 255, 255, 0); // 全透明白色作為遮罩前景
    // 填充整個畫布為背景色
    imagefill($big, 0, 0, $bgColorAlloc);

    // 繪製四個圓角扇形(背景色),實現「挖角」
    // 左上 (180-270)
    if ($corners['tl']) { imagefilledarc($big, $bigRadius, $bigRadius, $bigRadius*2, $bigRadius*2, 180, 270, $bgColorAlloc, IMG_ARC_PIE); }
    // 右上 (270-360/0)
    if ($corners['tr']) { imagefilledarc($big, $bigW - $bigRadius, $bigRadius, $bigRadius*2, $bigRadius*2, 270, 360, $bgColorAlloc, IMG_ARC_PIE); }
    // 右下 (0-90)
    if ($corners['br']) { imagefilledarc($big, $bigW - $bigRadius, $bigH - $bigRadius, $bigRadius*2, $bigRadius*2, 0, 90, $bgColorAlloc, IMG_ARC_PIE); }
    // 左下 (90-180)
    if ($corners['bl']) { imagefilledarc($big, $bigRadius, $bigH - $bigRadius, $bigRadius*2, $bigRadius*2, 90, 180, $bgColorAlloc, IMG_ARC_PIE); }

    // 5. 將源圖縮放貼到大畫布(保留透明通道)
    imagealphablending($big, true);
    imagesavealpha($big, true);
    imagecopyresampled($big, $srcImg, 0, 0, 0, 0, $bigW, $bigH, $w, $h);

    // 6. 縮回原尺寸(二次採樣平滑邊緣)
    $final = imagecreatetruecolor($w, $h);
    imagealphablending($final, false);
    imagesavealpha($final, true);
    $trans = imagecolorallocatealpha($final, 0, 0, 0, 127);
    imagefill($final, 0, 0, $trans);
    imagecopyresampled($final, $big, 0, 0, 0, 0, $w, $h, $bigW, $bigH);

    // 7. 輸出
    $save = match ($type) {
        IMAGETYPE_JPEG => fn() => imagejpeg($final, $dest, $quality),
        IMAGETYPE_PNG  => fn() => imagepng($dest, $dest, (int)round($quality/10*9)),
        IMAGETYPE_GIF  => fn() => imagegif($final, $dest),
        IMAGETYPE_WEBP => fn() => imagewebp($final, $dest, $quality),
        default => throw new RuntimeException("輸出格式不支援"),
    };
    $ok = $save();

    // 8. 清理
    imagedestroy($srcImg); imagedestroy($big); imagedestroy($final);
    return $ok;
}

使用範例

// 基本圓角
rounded_image('avatar.jpg', 'avatar_rounded.png', 30);

// 僅左上/右上圓角(卡片頂部)
rounded_image('card_bg.jpg', 'card_top.png', 16, ['tl'=>true, 'tr'=>true, 'br'=>false, 'bl'=>false], 'F0F0F0');

// 透明背景 PNG 圓角頭像
rounded_image('photo.png', 'avatar_circle.png', 9999, ['tl'=>true,'tr'=>true,'br'=>true,'bl'=>true], 'FFFFFF'); // 半徑大於邊長即圓形

關鍵技術點

  • 2x 超採樣:在 2 倍尺寸畫布繪製圓角,再縮回原尺寸,有效消除鋸齒,無需複雜貝塞爾曲線。
  • 遮罩邏輯:先填充背景色,再用背景色繪製扇形「挖角」,最後將源圖合成其上。背景色可為透明(PNG/WebP)或實色。
  • 真彩色 + Alpha 混合:imagecreatetruecolor + imagesavealpha(true) 保證透明通道正確疊加。
  • 圓形頭像技巧:半徑設為大於圖片短邊的值(如 9999),四角全開即得正圓。

現代替代:CSS / SVG / Imagick

方案優點缺點
CSS border-radius零後端成本、響應式、動畫友好、瀏覽器原生渲染無法生成實體圓角文件(需截圖)、打印/郵件模板不適用
SVG <clipPath>矢量無損、任意形狀、可直接內聯 HTML舊瀏覽器/郵件客戶端支援有限
Imagick roundCorners()單行調用、高性能、支援陰光、漸變邊框需安裝擴展、部署複雜
GD 本文方案純 PHP、零依賴、生成實體文件、完全可控代碼量大、大圖記憶體壓力、無向量優勢

Web 端展示優先 CSS;需生成文件(PDF 報表、郵件嵌入、App 靜態資源)時,GD 方案為通用兜底;高性能服務端圖像處理管線建議遷移至 php-vips (libvips 綁定)。

copyright © 萬盛學電腦網 all rights reserved