有時上傳圖片時由於圖片太大了,不只佔用空間,消耗流量,並且影響瀏(圖片的尺寸大小不一)。下面分享一種等比例不失真縮放圖片的方法,這樣,無論上傳的圖片尺有多大,都會自動壓縮到咱們設置尺寸值的範圍以內。通過測試,證實實用。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);//調用上面的函數
處理前圖片大小:1187*846html
圖片處理後大小:561*400web
處理後的圖片名稱:123.jpg網絡
寫在最後:由於客戶要求使用php實現等比例不失真縮放上傳圖片,原本要本身寫的,但百度一下發現了這個函數,因而乎就拿來用了,呵呵,省了我很多時間啊!其實咱們想到的一些新功能,網絡早已有之,猶其在中國,不少的創新,其實都是從國外翻譯過來的,在代碼這方面,老外的腦子確實很好使。上面的函數,做者不詳,但仍是要感謝做者的辛苦付出。函數