当前位置: 代码网 > it编程>编程语言>Php > 基于PHP封装图片裁剪工具类

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

2024年05月26日 Php 我要评论
php工具类图片裁剪类封装<?phpnamespace apputils; /** * 图片裁剪工具类 * @author田小涛 * @date2020年7月23日 * @comment

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图片裁剪的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com