php 无损压缩图片

基于composer
库中代码仅仅可以支持长宽比原图小的压缩参数,如需等于或者等于原图大小的需要调整代码;
实测压缩效果略低于tinypng ,但二次压缩会大小不变;
  • 该库方法有问题,结果显示,用tinypng压缩后的图片,用该库方法处理结果,图片会变大,效果相反!

  • 调整代码如下:

  /**
   * @param $picPath //待缩放的图片路径
   * @param $width //缩放的宽度,目标宽度;
   * @param $height //缩放的高度,目标高度;
   * @param bool $rotate //图片是否旋转
   * @return bool|string
   */
    public function pictureThumb($picPath,$width = '',$height = '',$rotate=false)//图片缩放
    {
        $imageInfo = $this->makeInternalImg($picPath);
        $picWidth = $imageInfo['imgInfo'][0];
        $picHeight = $imageInfo['imgInfo'][1];

        // added zb 如果未设置大小,抓取自身图片大小;
        if(!$width) $width = $picWidth;
        if(!$height) $height = $picHeight;

        if(!file_exists($picPath)) return false;
        $setRes = $this->setThumbImgPath($picPath,$width,$height);
        if(!is_null($setRes)) return $this->thumbOutPath;


        //根据参数$width和height值,换算出等比例缩放的宽度和高度
        $resizeWidthTag=$resizeHeightTag=false;
        $widthRatio=$heightRatio=0;
        $ratio = 0;//压缩比例
        if($width ){//&& $picWidth>$width chged zb
            $widthRatio = $width/$picWidth;
            $resizeWidthTag = true;
        }

        if($height ){//&& $picHeight>$height chged zb
            $heightRatio = $height/$picHeight;
            $resizeHeightTag = true;
        }

        if($resizeWidthTag && $resizeHeightTag){
            if($widthRatio<$heightRatio)
                $ratio = $widthRatio;
            else
                $ratio = $heightRatio;
        }

        if($resizeWidthTag && !$resizeHeightTag)
            $ratio = $widthRatio;

        if($resizeHeightTag && !$resizeWidthTag)
            $ratio = $heightRatio;

        $newWidth = $picWidth * $ratio;
        $newHeight = $picHeight * $ratio;

        //在内存中建立一个宽$width,高$height的真色彩画布
        $imageThumb=imagecreatetruecolor($newWidth,$newHeight);
        //将原图复制到新建的真色彩的画布上,并且按一定比例压缩
        imagecopyresampled($imageThumb,$imageInfo['src_img'],0,0,0,0,$newWidth,$newHeight,$imageInfo['imgInfo'][0],$imageInfo['imgInfo'][1]);
        imagedestroy($imageInfo['src_img']);

        if($rotate){
            $resource=$this->imageRotate($imageThumb,$degrees=90,$bgd_color=0);//旋转图片
            if(!$resource){
                return false;
            }
            $imageInfo['src_img']=$resource;
        }else{
            $imageInfo['src_img']=$imageThumb;
        }
        $this->destroyImg($imageInfo,$imageThumb);
        return $this->thumbOutPath;
    }
相信坚持的力量,日复一日的习惯.
原文地址:https://www.cnblogs.com/pansidong/p/15062765.html