以下是一个PHP类示例,用于给图片添加水印。这个类支持JPEG和PNG格式的图片,并允许你设置水印的位置(左上、右上、左下、右下或自定义位置)、透明度以及水印图片或文本。
``
`php
class ImageWatermark {
private $sourceImagePath;
private $watermarkImagePath = '';
private $watermarkText = '';
private $position = 'bottomRight'; // 可能的值:topLeft, topRight, bottomLeft, bottomRight, custom
private $x = 0;
private $y = 0;
private $opacity = 50; // 水印透明度,范围0-100
// 构造函数
public function __construct($sourceImagePath) {
$this->sourceImagePath = $sourceImagePath;
}
// 设置水印图片路径
public function setWatermarkImage($path) {
$this->watermarkImagePath = $path;
}
// 设置水印文本
public function setWatermarkText($text) {
$this->watermarkText = $text;
}
// 设置水印位置
public function setPosition($position, $x = 0, $y = 0) {
$this->position = $position;
if ($position === 'custom') {
$this->x = $x;
$this->y = $y;
}
}
// 设置水印透明度
public function setOpacity($opacity) {
$this->opacity = max(0, min(100, $opacity));
}
// 应用水印
public function applyWatermark() {
// 加载原图
list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($this->sourceImagePath);
switch ($sourceType) {
case IMAGETYPE_JPEG:
$sourceImage = imagecreatefromjpeg($this->sourceImagePath);
break;
case IMAGETYPE_PNG:
$sourceImage = imagecreatefrompng($this->sourceImagePath);
imagealphablending($sourceImage, false);
imagesavealpha($sourceImage, true);
break;
default:
throw new Exception('Unsupported image type.');
}
// 创建水印图片或文本
$watermarkImage = null;
if ($this->watermarkImagePath) {
$watermarkImage = imagecreatefrompng($this->watermarkImagePath);
} else {
// 假设使用白色文字
$textColor = imagecolorallocate($sourceImage, 255, 255, 255);
$watermarkImage = imagecreatetruecolor(strlen($this->watermarkText) * 10, 30);
imagealphablending($watermarkImage, false);
imagesavealpha($watermarkImage, true);
$transparent = imagecolorallocatealpha($watermarkImage, 0, 0, 0, 127);
imagefill($watermarkImage, 0, 0, $transparent);
imagestring($watermarkImage, 5, 5, 5, $this->watermarkText, $textColor);
}
// 设置水印位置
$watermarkWidth = imagesx($watermarkImage);
$watermarkHeight = imagesy($watermarkImage);
switch ($this->position) {
case 'topLeft':
$x = 5;
$y = 5;
break;
case 'topRight':
$x = $sourceWidth - $watermarkWidth - 5;
$y = 5;
break;
case 'bottomLeft':
$x = 5;
$y = $sourceHeight - $watermarkHeight - 5;
break;
case 'bottomRight':
$x = $sourceWidth - $watermarkWidth - 5;
$y = $sourceHeight - $watermarkHeight - 5;
break;
case 'custom':
$x = $this->x;
$y = $this->y;
break;
}
// 应用透明度
if ($this->watermarkImagePath) {
imagecopymerge($sourceImage, $watermarkImage, $x, $y, 0, 0, $watermarkWidth, $watermarkHeight, $this->opacity);
} else {
// 文本水印不支持直接的透明度调整,这里仅作为示例
imagecopy($sourceImage, $watermarkImage, $x, $y,