為保護圖片版權或品牌曝光,常需在上傳圖片自動加浮水印。PHP GD 提供兩種主流做法:文字水印(imagefttext() 需 TTF 字體檔)與 圖片水印(imagecopymerge() 支援半透明)。
$dst_path = 'dst.jpg';
$dst = imagecreatefromstring(file_get_contents($dst_path));
// 字體檔路徑(需確認伺服器有此檔案)
$font = './simsun.ttc';
$black = imagecolorallocate($dst, 0x00, 0x00, 0x00); // 黑色
// 參數:畫布、字體大小、角度、x、y、顏色、字體檔、文字
imagefttext($dst, 13, 0, 20, 20, $black, $font, '快樂編程');
// 依原圖類型輸出
list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
switch ($dst_type) {
case 1: header('Content-Type: image/gif'); imagegif($dst); break;
case 2: header('Content-Type: image/jpeg'); imagejpeg($dst); break;
case 3: header('Content-Type: image/png'); imagepng($dst); break;
}
imagedestroy($dst);

$dst_path = 'dst.jpg';
$src_path = 'src.jpg'; // 水印圖(如 Logo)
$dst = imagecreatefromstring(file_get_contents($dst_path));
$src = imagecreatefromstring(file_get_contents($src_path));
list($src_w, $src_h) = getimagesize($src_path);
// 參數:目標、來源、目標x、目標y、來源x、來源y、來源寬、來源高、透明度(0-100)
imagecopymerge($dst, $src, 10, 10, 0, 0, $src_w, $src_h, 50); // 50% 透明度
// 若水印圖本身帶 Alpha 通道(PNG),可改用 imagecopy() 保留原透明度
// imagecopy($dst, $src, 10, 10, 0, 0, $src_w, $src_h);
// 輸出邏輯同文字水印
list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
switch ($dst_type) {
case 1: header('Content-Type: image/gif'); imagegif($dst); break;
case 2: header('Content-Type: image/jpeg'); imagejpeg($dst); break;
case 3: header('Content-Type: image/png'); imagepng($dst); break;
}
imagedestroy($dst);
imagedestroy($src);

| 功能 | 函式 | 透明度支援 | 適用場景 |
|---|---|---|---|
| 文字水印 | imagefttext() | 需自行算色值模擬 | 動態文字(用戶名、時間戳) |
| 圖片水印 | imagecopymerge() | 0-100 整數透明度 | Logo、QR Code 等固定圖檔 |
| 圖片水印(含 Alpha) | imagecopy() | 完整 Alpha 通道 | PNG 透明 Logo |
simsun.ttc 或 msyh.ttc。imagedestroy()。imagecreatefromwebp() 等函式。