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

PHP 給圖片添加水印的兩種方式:圖片水印與文字水印

     編輯:PHP 綜合知識

方法一:圖片水印(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:獲取圖像寬、高、類型常量
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved