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

基于PHP封装图片裁剪工具类

基于PHP封装图片裁剪工具类

作者:许禾时间:2026-11-14 14:52:41浏览:474

本文介绍如何基于PHP语言封装一个实用的图片裁剪工具类。通过面向对象的设计思路,该类能够简化图片处理流程,提供便捷的接口以实现指定尺寸的图片截取功能,帮助开发者高效完成图像编辑任务。

本文目录展开

PHP图片裁剪工具类封装概述

本部分主要阐述如何利用PHP语言对图片裁剪功能进行面向对象式的封装,构建一个独立的工具类以简化开发过程中的图像处理逻辑。

<?php
namespace App\Utils;
 
 
 
/**
 * 图片裁剪工具类
 * @author	田小涛
 * @date	2020年7月23日
 * @comment
 *
 */
class ImageCropUtils
{
    
    private $sImage;
    private $dImage;
    private $src_file;
    private $dst_file;
    private $src_width;
    private $src_height;
    private $src_ext;
    private $src_type;
    private $mime;
    
    //上传基础路径处
    private $basisUploadPath;
    
    public function __construct( $file = null, $distFile = null )
    {
        $this->dst_file = $distFile;
        $this->basisUploadPath = storage_path( 'app/uploads/' );
        if( isset( $file ) && $file )
        {
            $this->src_file = $file;
            $this->init( $file );
        }
    }
 
    
    /**
     * 生成唯一的文件名称
     * @author	 Administrator
     * @datetime 2026年12月24日 上午11:44:02
     * @comment	
     * 
     * @param string $salt
     * @return string
     */
    protected function getUniqueDiskName($salt = '')
    {
        if( empty( $salt ) )
        {
            $salt = mt_rand(1,1000000);
        }
        list($usec, $sec) = explode(" ", microtime());
        
        $micros = str_replace('.', '', ((float)$usec + (float)$sec)).$salt;
        
        return md5( $micros );
    }
    
    
    /**
     * 初始化参数
     * @author	 Administrator
     * @datetime 2026年7月22日 下午3:00:22
     * @comment	
     * 
     * @return boolean
     */
    public function init( $url )
    {
        $strExt = $this->getImgExt( $url );
        $filename = $this->getUniqueDiskName( md5( $url ) );
        $path = date( 'y' ) . '/' . date( 'm' ) . '/' . date( 'd' ) . '/' . $filename;
        
        $dowRes = new \generalDowmload( $url,  $path . $strExt );
        if( !empty( $dowRes ) && isset( $dowRes->basename ) )
        {
            if( isset( $dowRes->location ) && strlen( $dowRes->location ) )
            {
                $this->src_file = $dowRes->location;
            }
            else
            {
                $this->src_file = $this->basisUploadPath .  $path . $strExt;
            }
        }
        else
        {
            return false;
        }
        if( !isset( $this->src_file ) || is_null( $this->src_file ) || !file_exists( $this->src_file ) )
        {
            return false;
        }
        
        $arrImageInfos = @getimagesize( $this->src_file );
        if( !isset( $arrImageInfos ) || empty( $arrImageInfos ) )
        {
            return false;
        }
        if( isset( $arrImageInfos[0] ) && $arrImageInfos[0] )
        {
            $this->src_width    = $arrImageInfos[0];
        }
        if( isset( $arrImageInfos[1] ) && $arrImageInfos[1] )
        {
            $this->src_height   = $arrImageInfos[1];
        }
        $this->src_type = 2;
        if( isset( $arrImageInfos[2] ) && $arrImageInfos[2] )
        {
            $this->src_type = $arrImageInfos[2];
        }
        if( isset( $arrImageInfos[ 'mime' ] ) )
        {
            $this->mime     = $arrImageInfos[ 'mime' ];
        }
        switch( $this->src_type ) 
        {
            case IMAGETYPE_JPEG :
                ini_set( 'gd.jpeg_ignore_warning', true );
                $this->sImage   =  @imagecreatefromjpeg( $this->src_file );
                $this->ext      =  'jpg';
                if( !isset( $this->mime ) || strlen( $this->mime ) <= 0 )
                {
                    $this->mime = 'image/jpeg';
                }
            break;
            case IMAGETYPE_PNG :
                $this->sImage   =  @imagecreatefrompng( $this->src_file );
                $this->ext      =  'png';
                if( !isset( $this->mime ) || strlen( $this->mime ) <= 0 )
                {
                    $this->mime = 'image/' . $this->ext;
                }
            break;
            case IMAGETYPE_GIF :
                $this->sImage   =  imagecreatefromgif( $this->src_file );
                $this->ext      =  'gif';
                if( !isset( $this->mime ) || strlen( $this->mime ) <= 0 )
                {
                    $this->mime = 'image/' . $this->ext;;
                }
            break;
            case 18:
                $this->sImage   = @imagecreatefromwebp( $this->src_file );
                $this->ext      =  'webp';
                if( !isset( $this->mime ) || strlen( $this->mime ) <= 0 )
                {
                    $this->mime = 'image/' . $this->ext;;
                }
            break;
            default:
                return false;
        }
        
        return true;
    }
    
    
    
    /**
     * 裁剪
     * @author	 Administrator
     * @datetime 2026年7月22日 下午3:07:36
     * @comment	
     * 
     * @param unknown $dst_width
     * @param unknown $dst_height
     * @param unknown $dst_x
     * @param unknown $dst_y
     * @param string $dst_file
     * @return boolean
     */
    public function cutImage( $dst_width, $dst_height, $dst_x, $dst_y, $originWidth, $originHeight )
    {
        if( !$dst_width || !$dst_height )
        {
            return false;
        }
 
        # 创建画布时,判断最终需要的画布大小
        if ($originWidth && $originHeight)
        {
            $dst_w = $originWidth;
            $dst_h = $originHeight;
        } 
        else
        {
            $dst_w = $dst_width;
            $dst_h = $dst_height;
        }
 
        $this->dImage = imagecreatetruecolor( $dst_w, $dst_h ); //创建了目标文件的大小的画布
        $bg = imagecolorallocatealpha( $this->dImage, 255, 255, 255, 127 ); //给画布分配颜色
        imagefill( $this->dImage, 0, 0, $bg ); //给图像用颜色进行填充
        imagecolortransparent( $this->dImage, $bg ); //背景定义成透明色
        
        $ratio_w = 1.0 * $dst_width / $this->src_width; //横向缩放的比例
        $ratio_h = 1.0 * $dst_height / $this->src_height; //纵向缩放的比例
        //不进行缩放,直接对图像进行裁剪
        $ratio = 1.0;
        $tmp_w = (int)($dst_width / $ratio);
        $tmp_h = (int)($dst_height / $ratio);
        
        $tmp_img = imagecreatetruecolor( $dst_width, $dst_height ); //创建暂时保存的画布
        imagecopy( $tmp_img, $this->sImage, 0, 0, $dst_x,$dst_y, $dst_width, $dst_height ); //拷贝出图像的一部分,进行裁切
        imagecopyresampled( $this->dImage, $tmp_img, 0, 0, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h ); //把暂时缓存的图片,放到目标文件里面
        imagedestroy( $tmp_img );
 
        return true;
    }
    
    
    /**
     * 存储
     * @author	 Administrator
     * @datetime 2026年7月22日 下午3:15:52
     * @comment	
     * 
     * @param unknown $file
     * @return boolean
     */
    public function save( $file = null )
    {
        if( !isset( $file ) || is_null( $file ) )
        {
            $this->dst_file = $this->src_file;
        }
        else
        {
            $this->dst_file = $this->basisUploadPath . '/'. $file;
        }
        try{
            switch( $this->src_type )
            {
                case IMAGETYPE_JPEG :
                    @imagejpeg( $this->dImage, $this->dst_file, 98 );
                break;
                case IMAGETYPE_PNG :
                    imagepng( $this->dImage, $this->dst_file );
                break;
                case IMAGETYPE_GIF :
                    imagegif( $this->dImage, $this->dst_file );
                break;
                case 18:
                    @imagejpeg( $this->dImage, $this->dst_file, 98 );
                break;
                default:
                    return false;
            }
        }catch( \Exception $e ){
            
        }
        
        $strExt = $this->getImgExt( $this->dst_file );
        
        $tmpImageInfo = @getimagesize( $this->dst_file );
        $width = 0;
        $height = 0;
        if( isset( $tmpImageInfo[0] ) && $tmpImageInfo[0] > 0 )
        {
            $width = $tmpImageInfo[0];
        }
        if( isset( $tmpImageInfo[1] ) && $tmpImageInfo[1] > 0 )
        {
            $height = $tmpImageInfo[1];
        }
        
        $objRet = new \stdClass();
        $objRet->mime       = $this->mime;
        $objRet->filename   = basename( $this->dst_file );
        $objRet->ext        = $strExt;
        $objRet->width      = $width;
        $objRet->height     = $height;
        
        return $objRet;
    }
    
    
    /**
     * 数据销毁
     * @author	 Administrator
     * @datetime 2026年7月22日 下午3:31:12
     * @comment	
     *
     */
    public function destroy()
    {
        imagedestroy( $this->sImage);
        imagedestroy( $this->dImage );
        @unlink( $this->src_file );
        
        return true;
    }
 
    /**
     * 检索图集是否存在后缀
     *  若不存在-则使用默认(强制转换)
     * @author	 Administrator
     * @datetime 2026年11月27日  下午3:30:47
     * @comment
     *
     * @param unknown $url
     * @return string|unknown
     */
    protected function getImgExt( $url )
    {
        
        $iLastSlash = strrpos( $url, '/' );
        $strFileName = mb_substr( $url, intval($iLastSlash+1) );
        $strExt = strrchr( $strFileName, '.' );
        preg_match( "/(.*?)\?.*?/", $strExt, $matches );
        if( !empty( $matches ) && isset( $matches[1] ) )
        {
            $strExt = $matches[1];
        }
        if( false == $strExt || is_null( $strExt ) || strlen( $strExt ) <= 0 )
        {
            $strExt = '.jpg';
        }
        
        return $strExt;
    }
    
    
}

在深入代码实现之前,有必要对相关的基础知识进行简要回顾与补充,确保读者理解后续操作所需的背景概念。

除核心的裁剪功能外,此处还汇总了利用PHP实现图片水印添加、图像压缩以及剪切等其他常用图像处理方法的封装技巧,旨在为开发者提供全面的参考。

<?php  

class Image
{    
    private $info;    private $image;    public $type;    public function construct($src)
    {

        $this->info=getimagesize($src);
        $this->type=image_type_to_extension($this->info['2'],false);
        $fun="imagecreatefrom{$this->type}";
        $this->image=$fun($src);
    }    /**
     * 文字水印
     * @param  [type]  $font     字体
     * @param  [type]  $content  内容
     * @param  [type]  $size     文字大小
     * @param  [type]  $col      文字颜色(四元数组)
     * @param  array   $location 位置 
     * @param  integer $angle    倾斜角度
     * @return [type]           
     */
    public function fontMark($font,$content,$size,$col,$location,$angle=0){
        $col=imagecolorallocatealpha($this->image, $col['0'], $col['1'], $col['2'],$col['3']);

        imagettftext($this->image, $size, $angle, $location['0'], $location['1'], $col,$font,$content);
    }    
    /**
     * 图片水印
     * @param  [type] $imageMark 水印图片地址
     * @param  [type] $dst       水印图片在原图片中的位置
     * @param  [type] $pct       透明度
     * @return [type]            
     */
    public function imageMark($imageMark,$dst,$pct){
        $info2=getimagesize($imageMark);
        $type=image_type_to_extension($info2['2'],false);
        $func2="imagecreatefrom".$type;
        $water=$func2($imageMark);

        imagecopymerge($this->image, $water, $dst[0], $dst[1], 0, 0, $info2['0'], $info2['1'], $pct);
        imagedestroy($water);

    }    /**
     * 压缩图片
     * @param  [type] $thumbSize 压缩图片大小
     * @return [type]            [description]     */
    public function thumb($thumbSize){
        $imageThumb=imagecreatetruecolor($thumbSize[0], $thumbSize[1]);
        
        imagecopyresampled($imageThumb, $this->image, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $this->info['0'], $this->info['1']);
        imagedestroy($this->image);
        $this->image=$imageThumb;
    }    /**
    * 裁剪图片
     * @param  [type] $cutSize  裁剪大小
     * @param  [type] $location 裁剪位置
     * @return [type]           [description]     */
     public function cut($cutSize,$location){
         $imageCut=imagecreatetruecolor($cutSize[0],$cutSize[1]);

         imagecopyresampled($imageCut, $this->image, 0, 0, $location[0], $location[1],$cutSize[0],$cutSize[1],$cutSize[0],$cutSize[1]);
         imagedestroy($this->image);
         $this->image=$imageCut;
     }    /**
     * 展现图片
     * @return [type] [description]     */
    public function show(){
        header("content-type:".$this->info['mime']);

        $funn="image".$this->type;

        $funn($this->image);
    }    /**
     * 保存图片
 * @param  [type] $newname 新图片名
 * @return [type]          [description] */
     public function save($newname){
         header("content-type:".$this->info['mime']);

         $funn="image".$this->type;

         $funn($this->image,$newname.'.'.$this->type);
     }     public function destruct(){
         imagedestroy($this->image);
     }

 }

上述内容详细展示了基于PHP封装图片裁剪工具类的具体实现方案。如需获取更多关于PHP图片处理的资料,建议查阅本站发布的其他相关文章。

上一篇
PHP三种方式读取RSA密钥加解密、签名验签完整教程

本文介绍在PHP中通过三种不同方式读取RSA公私钥,并实现数据的加密解密以及签名验证功能。内容涵盖从在线生成密钥到处理PEM格式字符串,再到使用openssl系列函数进行加解密和签名操作的具体步骤与代码封装。

下一篇
PHP防范SQL注入的三种核心策略与实现

针对PHP开发中常见的SQL注入漏洞,本文介绍了三种主要防护手段。首先阐述使用mysqli扩展进行参数化查询以隔离代码与数据;其次讲解利用filter_var和htmlspecialchars等函数对用户输入进行严格的格式验证与特殊字符转义;最后强调遵循最小权限原则限制数据库用户操作范围,结合系统更新构建多层次的安全防线。

相关文章

更多
PHP全功能无变形图片裁剪操作类与用法示例

本文介绍一个支持多种模式的PHP图片处理类,可实现任意尺寸裁剪、仅缩小不放大、保留全部信息补白缩放以及精确像素缩放。该类确保图片在变换过程中保持比例不变形,适用于生成高质量缩略图或定制尺寸图像,并提供相关在线工具推荐。

2025.11.01 379
PHP按比例截取图片的实现逻辑与工具推荐

本文介绍了在PHP中利用GD库实现图片按指定比例截取的核心方法,详细解析了宽高比判断与坐标计算逻辑。同时提供了多种实用的在线图片处理工具链接,涵盖格式转换、图标生成及Base64编码等功能,辅助开发者高效完成图像预处理任务。

2025.09.08 959
PHP无损图片裁剪与缩放函数实现

本文提供了一段PHP代码,用于将图片裁剪并缩放到指定尺寸,同时保持图像不变形且不留空白。该功能通过判断图像类型并调用相应的GD库函数实现,适用于需要统一图片尺寸的Web开发场景。

2025.06.01 728
PHP实现图片裁剪与添加水印功能

本文介绍利用PHP进行图片裁剪和添加水印的具体实现方法。通过相关函数,可以将原始图片按照指定尺寸进行裁剪处理,并在图像上叠加文字或图形水印,以满足内容保护或品牌展示的需求。

2026.09.28 125
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,033
PHP操作MySQL数据库:从工具选择到实战案例

本文介绍了使用PHP操作MySQL数据库的完整流程,涵盖命令行、Navicat及phpMyAdmin等常用管理工具。重点讲解HTTP GET与POST方式在表单数据传递中的区别与安全特性。通过mysqli扩展的基础步骤(创建连接、选择库、设置编码、执行SQL、关闭连接),演示了增删改查的具体实现,并对比了fetch_assoc、fetch_row和fetch_array三种结果集获取方法的差异。最后结合注册与登录两个实际案例,展示如何将前端用户输入安全地存入数据库并进行验证。

2026.01.07 1,005

专题推荐

更多
php图片裁剪

先确认目标尺寸和希望保留的画面区域。比例不同的图可先在裁剪工具里确认构图,再读等比截取或缩放案例。业务还需要水印时,参考组合示例检查裁剪和添加水印的顺序。

PHP 类与对象定义及继承

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

PHP 定时任务配置与运行

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

Yii2 队列配置与常驻运行

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

PHP Session 过期时间设置方法

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

在线工具箱

更多
图片裁剪
图片裁剪

从图片中截取需要的区域,重新安排主体位置与画面比例。

键码查询
键码查询

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

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

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

进制转换
进制转换

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

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

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