PHP图像裁剪工具类封装与实例代码

田小涛 2024-06-14 12:13:09编程技术
70

在网页设计和开发中,图像裁剪功能常常是不可或缺的一部分,尤其是在处理用户上传的头像或者产品图片时。为了满足这种需求,许多开发者会寻求高效的解决方案来实现这一功能。在这篇文章中,我们将详细介绍如何使用PHP封装一个图像裁剪工具类,并通过具体的代码实例来展示其实用性。

图像剪裁.png

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 2019年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 2020年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 2020年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 2020年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 2020年7月22日 下午3:31:12
     * @comment	
     *
     */
    public function destroy()
    {
        imagedestroy( $this->sImage);
        imagedestroy( $this->dImage );
        @unlink( $this->src_file );
        
        return true;
    }
 
    /**
     * 检索图集是否存在后缀
     *  若不存在-则使用默认(强制转换)
     * @author	 Administrator
     * @datetime 2018年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-&gt;type=image_type_to_extension($this-&gt;info['2'],false);
        $fun="imagecreatefrom{$this-&gt;type}";
        $this-&gt;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-&gt;image, $col['0'], $col['1'], $col['2'],$col['3']);

        imagettftext($this-&gt;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-&gt;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-&gt;image, 0, 0, 0, 0, $thumbSize[0], $thumbSize[1], $this-&gt;info['0'], $this-&gt;info['1']);
        imagedestroy($this-&gt;image);
        $this-&gt;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-&gt;image, 0, 0, $location[0], $location[1],$cutSize[0],$cutSize[1],$cutSize[0],$cutSize[1]);
         imagedestroy($this-&gt;image);
         $this-&gt;image=$imageCut;
     }    /**
     * 展现图片
     * @return [type] [description]     */
    public function show(){
        header("content-type:".$this-&gt;info['mime']);

        $funn="image".$this-&gt;type;

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

         $funn="image".$this-&gt;type;

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

 }

总结:

通过本文的介绍,我们了解了如何使用PHP创建一个强大的图像裁剪工具类。这个工具类不仅可以帮助我们轻松地完成图像裁剪任务,还可以提高我们的工作效率。希望本文的实例代码能够对大家有所帮助,让大家在实际项目中更加得心应手。当然,图像处理是一个非常广泛的话题,除了裁剪之外还有很多其他的功能等待大家去探索和学习。

php php代码 图像剪裁
THE END
ZhanShen
把烦恼扔进夕阳里,和星星一起沉沦。

相关推荐

站长如何选择合适的网页编程语言:ASP、PHP、ASP.NET的比较与选择
在当今数字化时代,网站建设对于个人和企业来说都至关重要。而选择合适的网页编程语言是构建一个成功网站的关键步骤之一。ASP、PHP 和ASP.NET是三种常见的网页编程语言,它们...
2024-09-01 站长之家
116

如何解决PHPStudy中MySQL启动后立即停止的问题
在使用PHPStudy进行Web开发的过程中,MySQL数据库服务器是不可或缺的一部分。然而,有时我们会遇到MySQL在启动后立即停止的情况,这不仅影响开发进度,也可能导致数据丢失。本...
2024-08-11 编程技术
154

VSCode+PHPstudy搭建配置PHP开发环境的方法详解
PHP作为一种广泛使用的脚本语言,仍然在网站开发中占据重要地位。对于开发者而言,选择合适的开发工具可以极大地提高工作效率。本文将详细介绍如何通过VSCode和PHPstudy来搭建...
2024-08-11 编程技术
122

PHP实现快速生成随机密码的几种方法
密码作为保护个人账户的第一道防线,其强度和复杂性直接决定了账户的安全水平。为了应对日益增长的安全需求,随机密码生成器成为了一种重要的工具。本文将探讨如何使用PHP快速...
2024-07-11 编程技术
127

PHP脚本模拟百度爬虫(User-Agent和IP)对目标网站进行抓取实例代码
在网络爬虫的世界里,模拟真实的用户行为或搜索引擎爬虫的行为是一种常见的技术。这种技术可以用于测试网站的抗压能力、分析竞争对手的网站数据,在本文中,我们将探讨如何使...
2024-06-20 编程技术
85

GD库助力PHP:轻松实现WebP到JPG格式转换
WebP是一种由谷歌开发的图像格式,它提供了比传统JPEG格式更高的压缩比和更佳的图像质量。然而,在某些情况下,我们仍然需要将WebP图像转换为更通用的JPG格式,以确保广泛的兼...
2024-06-17 编程技术
70