php實現等比例不失真縮放上傳圖片


有時上傳圖片時因為圖片太大了,不僅占用空間,消耗流量,而且影響瀏(圖片的尺寸大小不一)。下面分享一種等比例不失真縮放圖片的方法,這樣,不管上傳的圖片尺有多大,都會自動壓縮到我們設置尺寸值的范圍之內。經過測試,證明實用。
<?php 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);   }  } //使用方法: $im=imagecreatefromjpeg("./20140416103023202.jpg");//參數是圖片的存方路徑 $maxwidth="600";//設置圖片的最大寬度 $maxheight="400";//設置圖片的最大高度 $name="123";//圖片的名稱,隨便取吧 $filetype=".jpg";//圖片類型 resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//調用上面的函數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM