方法一:圖片水印(imagecopy)
<?php
$img = imagecreatefromjpeg($filename); // 背景圖
$logo = imagecreatefromjpeg($logo_filename); // 水印圖
// imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h)
imagecopy($img, $logo, 15, 15, 0, 0, $width, $height);
// 從 URL 獲取圖片內容
$url = 'https://example.com/image.jpg';
$content = file_get_contents($url);
$filename = 'tmp.jpg';
file_put_contents($filename, $content);
$img = imagecreatefromjpeg($filename);
$logo = imagecreatefrompng('logo.png');
$size = getimagesize('logo.png');
imagecopy($img, $logo, 15, 15, 0, 0, $size[0], $size[1]);
header("Content-Type: image/jpeg");
imagejpeg($img);
?>
方法二:文字水印(imagefttext)
<?php
$dst_path = 'https://example.com/photo.jpg';
$dst = imagecreatefromstring(file_get_contents($dst_path));
$font = './t1.ttf'; // 需真實 TTF 字體路徑
$black = imagecolorallocate($dst, 0, 0, 0);
// imagefttext($img, $size, $angle, $x, $y, $color, $fontfile, $text)
imagefttext($dst, 20, 0, 10, 30, $black, $font, 'Hello world!');
list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path);
switch ($dst_type) {
case 1: // GIF
header("Content-Type: image/gif");
imagegif($dst);
break;
case 2: // JPG
header("Content-Type: image/jpeg");
imagejpeg($dst);
break;
case 3: // PNG
header("Content-Type: image/png");
imagepng($dst);
break;
}
imagedestroy($dst);
?>
關鍵函數說明
imagecreatefromstring:從字符串創建圖像資源,自動識別格式
imagefttext:使用 FreeType 字體繪製文本,支援中文(需字體文件)
getimagesize:獲取圖像寬、高、類型常量
-