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);//傳參圖片

 

我是寫到一個類裏,爲了方便你們閱讀,拿出來了,若是本身項目裏用到,能夠也封裝起來,使用更方便,或者把擴展名判斷添加進類裏,你們能夠本身擴展,我比較懶,實現功能就行,懶得在深刻研究。但願你們工做順心。it

相關文章
相關標籤/搜索