添加水印很容易,我这里没考虑那么复杂,主要是控制水印位置在图片的右下角,和控制水印在图片中的大小。如,当目标图片与水印图大小接近,那么需要先等比缩放水印图片,再添加水印图片。

左边两幅图,上面是原图,下面是水印图,右边的缩放后加水印的新图。
4.类图

5.PHP代码
5.1. 构造函数 __construct()
在Image类中,除了构造函数__construct()是public,其它函数都为private.也就是在函数__construct()中,直接完成了生成缩略图和添加水印图的功能。如果,只生成缩略图而不需要添加水印,那么直接在__construct()的参数$markPath,设置为null即可。
其中,“$this->quality = $quality ? $quality : 75;” 控制输出为JPG图片时,控制图片质量(0-100),默认值为75;
/**
* Image constructor.
* @param string $imagePath 图片路径
* @param string $markPath 水印图片路径
* @param int $new_width 缩略图宽度
* @param int $new_height 缩略图高度
* @param int $quality JPG图片格输出质量
*/
public function __construct(string $imagePath,
string $markPath = null,
int $new_width = null,
int $new_height = null,
int $quality = 75)
{
$this->imgPath = $_SERVER['DOCUMENT_ROOT'] . $imagePath;
$this->waterMarkPath = $markPath;
$this->newWidth = $new_width ? $new_width : $this->width;
$this->newHeight = $new_height ? $new_height : $this->height;
$this->quality = $quality ? $quality : 75;
list($this->width, $this->height, $this->type) = getimagesize($this->imgPath);
$this->img = $this->_loadImg($this->imgPath, $this->type);
//生成缩略图
$this->_thumb();
//添加水印图片
if (!empty($this->waterMarkPath)) $this->_addWaterMark();
//输出图片
$this->_outputImg();
}
Note: 先生成缩略图,再在新图上添加水印 图片。
5.2. 生成缩略图函数_thumb()
/**
* 缩略图(按等比例,根据设置的宽度和高度进行裁剪)
*/
private function _thumb()
{
//如果原图本身小于缩略图,按原图长高
if ($this->newWidth > $this->width) $this->newWidth = $this->width;
if ($this->newHeight > $this->height) $this->newHeight = $this->height;
//背景图长高
$gd_width = $this->newWidth;
$gd_height = $this->newHeight;
//如果缩略图宽高,其中有一边等于原图的宽高,就直接裁剪
if ($gd_width == $this->width || $gd_height == $this->height) {
$this->newWidth = $this->width;
$this->newHeight = $this->height;
} else {
//计算缩放比率
$per = 1;
if (($this->newHeight / $this->height) > ($this->newWidth / $this->width)) {
$per = $this->newHeight / $this->height;
} else {
$per = $this->newWidth / $this->width;
}
if ($per < 1) {
$this->newWidth = $this->width * $per;
$this->newHeight = $this->height * $per;
}
}
$this->newImg = $this->_CreateImg($gd_width, $gd_height, $this->type);
imagecopyresampled($this->newImg, $this->img, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
}







