PHP图片压缩

<?php
/**
 * Created by PhpStorm.
 * User: 20170720李雁飞
 * Date: 2018/9/24
 * Time: 0:10
 */

class ImgCompress
{
    static private $_instance = null;
    private $src;
    private $image;
    private $imageinfo;
    private $press_image_width = 1200;
    private $press_image_height = 858;
    private $quality = 100;

    /**
     * 图片压缩
     * @param $src 源图
     * @param float $percent  压缩比例
     */
    static function GetInstance()
    {
        if (null == self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /** 高清压缩图片
     * @param string $saveName  提供图片名
     */
    public function compressImg($src,$saveName,$press_image_width = 1200,$press_image_height = 858)
    {
        $this->src = $src;
        $this->press_image_width = $press_image_width;
        $this-> press_image_height = $press_image_height;
        $this->_openImage();
        return $this->_saveImage($saveName);  //保存
    }

    /**
     * 内部:打开图片
     */
    private function _openImage()
    {
        list($width, $height, $type, $attr) = getimagesize($this->src);
        $this->imageinfo = array(
            'width'=>$width,
            'height'=>$height,
            'type'=>image_type_to_extension($type,false),
            'attr'=>$attr
        );
        $fun = "imagecreatefrom".$this->imageinfo['type'];
        $this->image = $fun($this->src);
        $this->_thumpImage();
    }
    /**
     * 内部:操作图片
     */
    private function _thumpImage()
    {
        $new_width = $this->press_image_width;
        $new_height = $this->press_image_height;
        $image_thump = imagecreatetruecolor($new_width,$new_height);
        //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
        imagecopyresampled($image_thump,$this->image,0,0,0,0,$new_width,$new_height,$this->imageinfo['width'],$this->imageinfo['height']);
        imagedestroy($this->image);
        $this->image = $image_thump;
    }

    private function _saveImage($dstImgName)
    {
        $funcs = "imagejpeg";
        $ret = $funcs($this->image,$dstImgName);

        return $ret;
    }

    /**
     * 销毁图片
     */
    public function __destruct(){
        imagedestroy($this->image);
    }

}

版权声明:
作者:ForDream
链接:https://ishoud.com/index.php/2021/08/24/111.html
来源:工具人
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
PHP图片压缩
<?php /**  * Created by PhpStorm.  * User: 20170720李雁飞  * Date: 2018/9/24  * Time: 0:10  */ class ImgCompress {     static private ……
<<上一篇
下一篇>>