图片压缩

  • 将图片压缩成jpg或png
    $type = explode('/', $file->type);
    $mainType = $type[0];
    $subType = $type[1];
    $isImage = $mainType == 'image';
    $isGif = $subType == 'gif';//gif压缩会变静态的,所以过滤掉
    if ($isImage) {
        $maxSize = 1024 * 1024;
        if (!$isGif) {
            //图片进行压缩
            $file->data = $this->compressImage($file->data, $maxSize);
        }
        //生成文件
    }
    
    function compressImage($data, $maxSize, $percent = 1) {
        $size = strlen($data);
        if ($size <= $maxSize) {
            return $data;
        }
    
        $img = imagecreatefromstring($data);
        $width = imagesx($img);
        $height = imagesy($img);
    
        $newWidth = $width * $percent;
        $newHeight = $height * $percent;
    
        $newImg = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($newImg, $img, 0, 0, 0, 0, floor($newWidth), floor($newHeight), $width, $height);
    
        ob_start(); //Turn on output buffering
        imagepng($newImg); //Generate your image
        //imagejpeg($newImg); 
        $data = $output = ob_get_contents(); // get the image as a string in a variable
        ob_end_clean(); //Turn off output buffering and clean it
        imagedestroy($newImg);
        $percent -= 0.1;
        print_r("\npercent={$percent},size={$size}");
        return self::compressImage($data, $maxSize,$percent);
    }

     

  • jpg
    • 4.58M:(1)710KB[4]
    • 3.78M:(2)267KB[1]
    • 1.38M:(3)718KB[1]
  • png
    • 4.58M:(1)997.29[6]
    • 3.78M:(2)982.2KB[4]
    • 1.38M:(3)928KB[5]

转载于:https://www.cnblogs.com/fatRabbit-/p/11393442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值