分享按钮

压缩图片不改变图片路径---执行此方法压缩所有图片

默认分类 / 7182人浏览 / 0人评论

压缩图片不改变图片路径---执行此方法压缩所有图片

public function ysuo_img()
{
   set_time_limit(10000);  //超时时间由于需要遍历整个文件夹 需要设置更长一点的超时时间
   $resource = opendir("./uploads");//本地文件夹路径 一般是项目根目录下的public/uploads
   while ($row = readdir($resource)) { //遍历一级文件夹
       if(is_dir('./uploads/'.$row)){ //判断是否有该文件
           if($row == "." || $row == ".."){continue;} //没有则跳出循环
           $resource1 = opendir('./uploads/'.$row); //打开二级文件夹
           while ($row1 = readdir($resource1)) { //循环读取二级文件夹文件 由于我的图片文件路径是 uploads/2001120122/xxx.png 所以用了2层循环 具体循环层级根据自己的文件路径配置
               if($row1 == "." || $row1 == ".."){continue;}  //没有则跳出循环
               $img = './uploads/'.$row.'/'.$row1;  //需要压缩的绝对路径文件地址
               // 大于200K
               if(filesize($img) > 100000){    //可以压缩的文件大小默认是字节数
                   $ret = getimagesize($img); //获取文件尺寸信息
                   if($ret[0] > 450){ //默认大于450的宽度比例
                       $width = 450;
                       $height = $ret[1]*(450/$ret[0]);
                   }else{
                       $width = $ret[0];
                       $height = $ret[1];
                   }
                   image_png_size_adds($img,$img,$width,$height); //替换压缩后的图片路径
               }else{
                   dump(2);
               }
           }
           closedir($resource1);
       }else{
       }
   }
   closedir($resource);
}

/**
* desription 压缩图片
* @param sting $imgsrc 图片路径
* @param string $imgdst 压缩后保存路径
*/
function image_png_size_adds($imgsrc,$imgdst,$img_width,$img_height){
   list($width,$height,$type)=getimagesize($imgsrc);
   $new_width = $img_width;
   $new_height = $img_height;

   switch($type){
       case 1:
           $giftype=check_gifcartoon($imgsrc);
           if($giftype){
               $image_wp=imagecreatetruecolor($new_width, $new_height);
               $image = imagecreatefromgif($imgsrc);
               imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
               imagejpeg($image_wp, $imgdst,75);
               imagedestroy($image_wp);
           }
           break;
       case 2:
           $image_wp=imagecreatetruecolor($new_width, $new_height);
           $image = imagecreatefromjpeg($imgsrc);
           imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
           imagejpeg($image_wp, $imgdst,100);
           imagedestroy($image_wp);
           break;
       case 3:
           $image_wp=imagecreatetruecolor($new_width, $new_height);
           $image = imagecreatefrompng($imgsrc);
           imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
           imagejpeg($image_wp, $imgdst,75);
           imagedestroy($image_wp);
           break;
   }
}


感谢博主,喝杯咖啡~