php压缩图片类,用gd库函数,吸取网上前辈精华加自己修改

上传图片时候后台等比例压缩,可以节省带宽,适用于上传头像或者某些可以压缩的图片,相册的话不建议使用

项目中用到了一个图片压缩,本来打算用imagemagick,但是考虑到需要在服务器端安装太多插件,为了一个程序太麻烦了,感谢网上前辈的恩惠,搜到了一段直接拿来用,出处不详,贴出来大家共勉

function resizeImage($im,$maxwidth,$maxheight,$name,$filetype)
 {
  $pic_width = imagesx($im);
  $pic_height = imagesy($im);
 
  if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
  {
   if($maxwidth && $pic_width>$maxwidth)
   {
    $widthratio = $maxwidth/$pic_width;
    $resizewidth_tag = true;
   }
 
   if($maxheight && $pic_height>$maxheight)
   {
    $heightratio = $maxheight/$pic_height;
    $resizeheight_tag = true;
   }
 
   if($resizewidth_tag && $resizeheight_tag)
   {
    if($widthratio<$heightratio)
     $ratio = $widthratio;
    else
     $ratio = $heightratio;
   }
 
   if($resizewidth_tag && !$resizeheight_tag)
    $ratio = $widthratio;
   if($resizeheight_tag && !$resizewidth_tag)
    $ratio = $heightratio;
 
   $newwidth = $pic_width * $ratio;
   $newheight = $pic_height * $ratio;
 
   if(function_exists("imagecopyresampled"))
   {
    $newim = imagecreatetruecolor($newwidth,$newheight);//PHP系统函数
      imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
   }
   else
   {
    $newim = imagecreate($newwidth,$newheight);
      imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
   }
 
   $name = $name.$filetype;
   imagejpeg($newim,$name);
   imagedestroy($newim);
  }
  else
  {
   $name = $name.$filetype;
   imagejpeg($im,$name);
  }
 }

 

 

使用方法


        $pathimg="图片地址路径加完整扩展名";
        $patharr=pathinfo($pathimg); //判断图片类型,我这里只需要四种,如果需要的朋友们可以使用其他,自己添加进去即可
        switch ($patharr['extension']) {
          case 'jpg':
                $im=imagecreatefromjpeg($pathimg);
                break;
          case 'jpeg':
                $im=imagecreatefromjpeg($pathimg);
                break;
          case 'gif':
                $im=imagecreatefromgif($pathimg);
                break;
          case 'png':
                $im=imagecreatefrompng($pathimg);
                break;
        }
       
        $maxwidth="600";//设置图片的最大宽度
        $maxheight="600";//设置图片的最大高度
        $name=$pathimg;//图片的名称,随便取吧
        $filetype="";//图片类型 如果想要限制图片类型为特定格式,那$name用一个basename去掉扩展名,这里填写后缀即可,我这是在源文件地址替换,如果想要压缩后换文件夹,也可以再$name里直接把新的路径加上
        resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//传参

 

我是写到一个类里,为了方便大家阅读,拿出来了,如果自己项目里用到,可以也封装起来,使用更方便,或者把扩展名判断添加进类里,大家可以自己扩展,我比较懒,实现功能就行,懒得在深入研究。希望大家工作顺心。

 

转载于:https://my.oschina.net/u/2366458/blog/592017

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值