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

來源:互聯網
上載者:User

標籤:

有時上傳圖片時因為圖片太大了,不僅佔用空間,消耗流量,而且影響瀏(圖片的尺寸大小不一)。下面分享一種等比例不失真縮放圖片的方法,這樣,不管上傳的圖片尺有多大,都會自動壓縮到我們設定尺寸值的範圍之內。經過測試,證明實用。
<?phpfunction 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);//調用上面的函數

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.