当前位置: 首页 > 编程文章 >

PHP Image类实现等比缩略图与右下角水印功能

PHP Image类实现等比缩略图与右下角水印功能

作者:沈澄时间:2025-09-22 13:44:02浏览:783

本文介绍一个PHP Image类,用于在上传图片时自动生成缩略图并添加水印。核心逻辑通过比较新图与原图的宽高比确定缩放比率,确保不出现黑边且保持比例。水印默认置于右下角,若目标图较小则先等比缩小水印。该类支持JPG质量控制,但无法处理GIF动画帧。

本文目录收起

PHP Image类实现等比缩略图与右下角水印功能

1.开始

在网站上传图片过程中,缩略图功能是常见需求。这里分享一个自行编写的图片处理Image类,它具备生成缩略图以及为图片添加水印的功能。

2.如何生成缩略图

生成缩略图的核心在于如何准确计算缩放比率。

基于图片等比缩放的原则,针对宽高的几种常见变化,得出一种计算缩放比率的算法:使用新图(即缩略图)的宽高分别除以原图的对应宽高,取其中较大的值作为最终的缩放比率:

缩放比率 = Max( { 新图高度 / 原图高度 , 新图宽度 / 原图宽度 } )

具体逻辑表现为:

If ( (新图高度 / 原图高度) > (新图宽度 / 原图宽度 ) ) {

缩放比率 = 新图高度 / 原图高度;

}ELSE {

缩放比率 = 新图宽度 / 原图宽度;

     }

以下列出不同场景下的图片缩放处理方式:

e.g

场景1,原图比新图大的情况, 缩放比率 = 新图宽度 / 原图宽度 :

场景2,原图比新图大的情况,b. 缩放比率 = 新图高度 / 原图高度 :

场景3,原图比新图大的情况,而且新图宽高相等,即新图形状是正方形,那么上面的缩放算法也是适用的。

场景4,如果 “新图宽度 >= 原图宽度” ,同时 “新图高度 >= 原图高度”,那么不缩放图片,也不放大图片,保持原图。

场景5,如果 “新图宽度 < 原图宽度”,同时 “新图高度 >= 原图高度” ,那么先设置 “新图高度= 原图高度”,再剪切。

场景6,如果 “新图高度 < 原图高度”,同时 “新图宽度 >= 原图宽度” ,那么先设置 “新图宽度= 原图宽度”,再剪切。

3.如何添加水印图片 添加水印相对简单,主要控制水印位置在图片的右下角,以及控制水印在图片中的大小。例如,当目标图片与水印图大小接近时,需要先等比缩放水印图片,然后再将其添加到目标图上。

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

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);
  }

生成缩略图函数_thumb() ,是按照前面的分析来进行编码。

5.3. 添加水印图片函数 _addWaterMark()


   /**
   * 添加水印
   */
  private function _addWaterMark()
  {
    $ratio = 1 / 5; //水印缩放比率

    $Width = imagesx($this->newImg);
    $Height = imagesy($this->newImg);

    $n_width = $Width * $ratio;
    $n_height = $Width * $ratio;

    list($markWidth, $markHeight, $markType) = getimagesize($this->waterMarkPath);

    if ($n_width > $markWidth) $n_width = $markWidth;
    if ($n_height > $markHeight) $n_height = $markHeight;

    $Img = $this->_loadImg($this->waterMarkPath, $markType);
    $Img = $this->_thumb1($Img, $markWidth, $markHeight, $markType, $n_width, $n_height);
    $markWidth = imagesx($Img);
    $markHeight = imagesy($Img);
    imagecopyresampled($this->newImg, $Img, $Width - $markWidth - 10, $Height - $markHeight - 10, 0, 0, $markWidth, $markHeight, $markWidth, $markHeight);
    imagedestroy($Img);
  }

在添加水印图片中,用到一个_thumb1()函数来缩放水印图片:


  /**
   * 缩略图(按等比例)
   * @param resource $img 图像流
   * @param int $width
   * @param int $height
   * @param int $type
   * @param int $new_width
   * @param int $new_height
   * @return resource
   */
  private function _thumb1($img, $width, $height, $type, $new_width, $new_height)
  {

    if ($width < $height) {
      $new_width = ($new_height / $height) * $width;
    } else {
      $new_height = ($new_width / $width) * $height;
    }

    $newImg = $this->_CreateImg($new_width, $new_height, $type);
    imagecopyresampled($newImg, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    return $newImg;
  }


5.4. 完整代码:


<?php

/**
 * 图片处理,生成缩略图和添加水印图片
 * Created by PhpStorm.
 * User: andy
 * Date: 17-1-3
 * Time: 上午11:55
 */
class Image
{
 //原图
 private $imgPath; //图片地址
 private $width;  //图片宽度
 private $height; //图片高度
 private $type;  //图片类型
 private $img;  //图片(图像流)

 //缩略图
 private $newImg; //缩略图(图像流)
 private $newWidth;
 private $newHeight;

 //水印图路径
 private $waterMarkPath;

 //输出图像质量,jpg有效
 private $quality;

 /**
  * 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();
 }

 /**
  *图片输出
  */
 private function _outputImg()
 {
  switch ($this->type) {
   case 1: // GIF
    imagegif($this->newImg, $this->imgPath);
    break;
   case 2: // JPG
    if (intval($this->quality) < 0 || intval($this->quality) > 100) $this->quality = 75;
    imagejpeg($this->newImg, $this->imgPath, $this->quality);
    break;
   case 3: // PNG
    imagepng($this->newImg, $this->imgPath);
    break;
  }
  imagedestroy($this->newImg);
  imagedestroy($this->img);
 }

 /**
  * 添加水印
  */
 private function _addWaterMark()
 {
  $ratio = 1 / 5; //水印缩放比率

  $Width = imagesx($this->newImg);
  $Height = imagesy($this->newImg);

  $n_width = $Width * $ratio;
  $n_height = $Width * $ratio;

  list($markWidth, $markHeight, $markType) = getimagesize($this->waterMarkPath);

  if ($n_width > $markWidth) $n_width = $markWidth;
  if ($n_height > $markHeight) $n_height = $markHeight;

  $Img = $this->_loadImg($this->waterMarkPath, $markType);
  $Img = $this->_thumb1($Img, $markWidth, $markHeight, $markType, $n_width, $n_height);
  $markWidth = imagesx($Img);
  $markHeight = imagesy($Img);
  imagecopyresampled($this->newImg, $Img, $Width - $markWidth - 10, $Height - $markHeight - 10, 0, 0, $markWidth, $markHeight, $markWidth, $markHeight);
  imagedestroy($Img);
 }

 /**
  * 缩略图(按等比例,根据设置的宽度和高度进行裁剪)
  */
 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);
 }


 /**
  * 缩略图(按等比例)
  * @param resource $img 图像流
  * @param int $width
  * @param int $height
  * @param int $type
  * @param int $new_width
  * @param int $new_height
  * @return resource
  */
 private function _thumb1($img, $width, $height, $type, $new_width, $new_height)
 {

  if ($width < $height) {
   $new_width = ($new_height / $height) * $width;
  } else {
   $new_height = ($new_width / $width) * $height;
  }

  $newImg = $this->_CreateImg($new_width, $new_height, $type);
  imagecopyresampled($newImg, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
  return $newImg;
 }

 /**
  * 加载图片
  * @param string $imgPath
  * @param int $type
  * @return resource
  */
 private function _loadImg($imgPath, $type)
 {
  switch ($type) {
   case 1: // GIF
    $img = imagecreatefromgif($imgPath);
    break;
   case 2: // JPG
    $img = imagecreatefromjpeg($imgPath);
    break;
   case 3: // PNG
    $img = imagecreatefrompng($imgPath);
    break;
   default: //其他类型
    Tool::alertBack('不支持当前图片类型.' . $type);
    break;
  }
  return $img;
 }

 /**
  * 创建一个背景图像
  * @param int $width
  * @param int $height
  * @param int $type
  * @return resource
  */
 private function _CreateImg($width, $height, $type)
 {
  $img = imagecreatetruecolor($width, $height);
  switch ($type) {
   case 3: //png
    imagecolortransparent($img, 0); //设置背景为透明的
    imagealphablending($img, false);
    imagesavealpha($img, true);
    break;
   case 4://gif
    imagecolortransparent($img, 0);
    break;
  }

  return $img;
 }
}


6.调用

调用非常简单,在引入类后,直接new 并输入对应参数即可:

e.g.

new Image($_path, MARK, 400, 200, 100);

7.小结 这个Image 类能够生成缩略图,不出现黑边,添加水印图,能根据图片的大小缩放水印图。当然有个缺点,就是不能缩放GIF的动画,因为涉及到帧的处理,比较麻烦。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

上一篇
Laravel Crontab 定时任务不执行的排查与解决

在 Laravel 项目中配置 Crontab 定时任务时,若手动执行 artisan 命令有效但系统计划任务无反应,通常是因为 Crontab 环境中的 PHP 可执行文件路径与脚本中使用的路径不一致。通过 whereis php 命令确认正确的 PHP 绝对路径,并在 crontab 配置中替换默认 php 调用,即可解决该问题。

下一篇
PHP单链表实现代码分享

本文提供了PHP语言中单链表的完整实现代码。通过具体的类定义与方法封装,展示了节点创建、插入、删除及遍历等核心操作,旨在为开发者提供可直接参考的技术方案,帮助理解并掌握线性表在PHP中的编程实践。

相关文章

更多
PHP实现图片等比例缩放生成缩略图

该PHP函数通过计算原图与目标尺寸的宽高比,自动选择较小的比例以确保图片不变形。利用GD库的imagecopyresampled或imagecopyresized函数创建新画布并复制图像,最终保存为指定格式的缩略图文件,同时处理资源释放。

2025.04.02 996
PHP实现水印文字和缩略图的方法示例

本文介绍在PHP中利用GD库为图片添加文字水印及生成缩略图的具体实现方法。通过相关函数调用,开发者可以轻松对图像进行基础处理,满足网站展示或版权保护需求。该方法代码简洁,适合PHP程序设计参考。

2025.12.17 966
PHP按百分比生成缩略图函数实现

本文介绍了一个无需使用类、仅通过单个函数即可实现的PHP缩略图生成方案。该程序基于GD库,默认支持按百分比进行等比缩放,同时也允许指定具体的长宽尺寸。代码内部注释详尽,旨在帮助开发者快速理解核心逻辑并应用于实际项目中。

2025.01.30 832
支持PNG透明背景的PHP缩略图生成类

针对原有PHP图片处理库在生成PNG缩略图时出现格式错误及透明背景丢失的问题,本文分享一个基于GD2图形库优化的PHP缩略图生成类。该类修正了PNG输出格式、保留半透明效果并更新语法,通过构造函数传入原图路径、宽高、裁剪开关及保存路径即可快速调用。

2026.01.08 567
PHP实现上传图片生成缩略图示例

本文提供了一段PHP代码,用于实现上传图片并自动生成缩略图的功能。代码中包含详细注释,便于开发者理解和使用。该功能适用于需要处理用户上传图像的Web应用,能够自动创建指定尺寸的缩略图,节省存储空间并提升页面加载速度。

2025.07.02 144
PHP图片处理类实现文字水印、缩略图及图片水印示例

本文介绍一个名为ImageToTest的PHP类,用于实现图片的文字水印、缩略图裁剪及图片叠加水印功能。该类通过构造函数加载图片资源,提供thumb方法调整尺寸,fontMark方法添加自定义字体水印,以及imageMark方法合成其他图片作为水印。测试代码展示了如何实例化该类并调用相应方法完成图片编辑操作。

2026.02.21 970

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。