為上傳圖片加上浮水印是保護版權的常見需求。本文提供完整實作,支援 JPEG/GIF 格式、PNG 浮水印、隨機位置放置與表單上傳整合。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>圖片浮水印上傳</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table align="center" cellpadding="5">
<tr>
<td>選擇圖片:</td>
<td><input type="file" name="upfile" accept="image/jpeg,image/gif" required></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="上傳並加浮水印">
</td>
</tr>
</table>
<input type="hidden" name="action" value="doup">
</form>
</body>
</html>
<?php
if (($_POST['action'] ?? '') === 'doup') {
// 設定
$allowedTypes = ['image/jpeg', 'image/pjpeg', 'image/jpg', 'image/gif'];
$waterMarkPath = 'water.png'; // 建議使用 PNG 含透明通道
$uploadDir = __DIR__ . '/uploads/';
// 確保上傳目錄存在
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$file = $_FILES['upfile'] ?? null;
// 驗證上傳
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
die('上傳失敗或無檔案');
}
if (!in_array($file['type'], $allowedTypes)) {
die('不支援的檔案格式,僅限 JPEG/GIF');
}
// 檢查浮水印檔案
if (!file_exists($waterMarkPath)) {
die("浮水印檔案不存在: {$waterMarkPath}");
}
// 根據類型建立圖片資源
$sourceImage = null;
if (strpos($file['type'], 'jpeg') !== false || strpos($file['type'], 'jpg') !== false) {
$sourceImage = imagecreatefromjpeg($file['tmp_name']);
} elseif ($file['type'] === 'image/gif') {
$sourceImage = imagecreatefromgif($file['tmp_name']);
}
if (!$sourceImage) {
die('無法讀取上傳圖片');
}
$srcW = imagesx($sourceImage);
$srcH = imagesy($sourceImage);
// 載入浮水印
$waterMark = imagecreatefrompng($waterMarkPath);
$wmW = imagesx($waterMark);
$wmH = imagesy($waterMark);
// 啟用混合模式(支援透明度)
imagealphablending($sourceImage, true);
imagesavealpha($sourceImage, true);
// 隨機位置:四個角落
$positions = [
[5, 5], // 左上
[$srcW - $wmW - 5, 5], // 右上
[5, $srcH - $wmH - 5], // 左下
[$srcW - $wmW - 5, $srcH - $wmH - 5] // 右下
];
$pos = $positions[array_rand($positions)];
// 複製浮水印到源圖片
imagecopy($sourceImage, $waterMark, $pos[0], $pos[1], 0, 0, $wmW, $wmH);
// 輸出處理後圖片
$outputName = 'watermarked_' . basename($file['name']);
$outputPath = $uploadDir . $outputName;
if (strpos($file['type'], 'jpeg') !== false || strpos($file['type'], 'jpg') !== false) {
imagejpeg($sourceImage, $outputPath, 90);
} else {
imagegif($sourceImage, $outputPath);
}
// 釋放資源
imagedestroy($sourceImage);
imagedestroy($waterMark);
echo "<p>處理完成!</p>";
echo "<img src='{$outputPath}' alt='浮水印結果'>";
}
?>
// 關鍵設定:啟用 Alpha 混合並保存 Alpha 通道
imagealphablending($dest, true);
imagesavealpha($dest, true);
注意: GD 庫處理 GIF 時僅處理第一幀。若需支援動畫 GIF 浮水印,需使用 ImageMagick (imagick 擴展)。
<?php
// 大圖片處理前調整記憶體限制
ini_set('memory_limit', '256M');
// 或在 php.ini: memory_limit = 256M
?>
<?php
// 文字浮水印範例
$fontPath = __DIR__ . '/fonts/DejaVuSans.ttf';
$text = 'Copyright © 2024';
$color = imagecolorallocatealpha($sourceImage, 255, 255, 255, 50); // 白色半透明
// 計算文字位置(右下角)
$bbox = imagettfbbox(20, 0, $fontPath, $text);
$textW = $bbox[2] - $bbox[0];
$textH = $bbox[1] - $bbox[7];
$x = $srcW - $textW - 10;
$y = $srcH - 10;
imagettftext($sourceImage, 20, 0, $x, $y, $color, $fontPath, $text);
?>
| 問題 | 原因 | 解決方案 |
|---|---|---|
| 浮水印不顯示 | 座標超出圖片範圍 | 檢查 $pos[0], $pos[1] 不超過圖片寬高 |
| PNG 透明變黑底 | 未啟用 alphablending | 加上 imagealphablending() 與 imagesavealpha() |
| 記憶體耗盡 | 大圖片處理超過 memory_limit | 調整 memory_limit 或縮圖後再加浮水印 |
| GIF 動畫靜止 | GD 只處理第一幀 | 改用 ImageMagick |