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

PHP GD 實作文字水印與圖片水印(含半透明效果)

     編輯:PHP 相關知識

為保護圖片版權或品牌曝光,常需在上傳圖片自動加浮水印。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

部署提醒

  • 文字水印需 TTF 字體檔,Linux 伺服器常缺中文字體,建議專案自帶 simsun.ttc 或 msyh.ttc。
  • 大量加水印時注意記憶體用量,處理完立即 imagedestroy()。
  • 若需支援 WebP、AVIF 等新格式,需 PHP 7.2+ 搭配 imagecreatefromwebp() 等函式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved