上傳圖片時候後臺等比例壓縮,能夠節省帶寬,適用於上傳頭像或者某些能夠壓縮的圖片,相冊的話不建議使用服務器
項目中用到了一個圖片壓縮,原本打算用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); } } |
使用方法插件
我是寫到一個類裏,爲了方便你們閱讀,拿出來了,若是本身項目裏用到,能夠也封裝起來,使用更方便,或者把擴展名判斷添加進類裏,你們能夠本身擴展,我比較懶,實現功能就行,懶得在深刻研究。但願你們工做順心。it |