/** 图片压缩函数 * @param $orgin_file 原始图片文件 * @param $maxwidth 最大宽度 * @param $maxheight 最大高度 * @param $name 压缩图片名 * @param $filetype 图片类型 */ function resizeImage($orgin_file,$maxwidth,$maxheight,$name,$filetype) { $im = ''; switch ($filetype){ case '.jpg': $im=imagecreatefromjpeg($orgin_file); break; case '.png': $im=imagecreatefrompng($orgin_file); break; case '.gif': $im=imagecreatefromgif($orgin_file); break; default: $im=imagecreatefromgd($orgin_file); } $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; switch ($filetype){ case '.jpg': imagejpeg($newim,$name); break; case '.png': imagepng($newim,$name); break; case '.gif': imagegif($newim,$name); break; default: imagegd($newim,$name); } imagedestroy($newim); } else { $name = $name.$filetype; switch ($filetype){ case '.jpg': imagejpeg($im,$name); break; case '.png': imagepng($im,$name); break; case '.gif': imagegif($im,$name); break; default: imagegd($im,$name); } } }
以上就介紹了 PHP壓縮圖片函數,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。