function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) { list($width, $height, $type, $attr) = getimagesize($srcImage); if($width < $maxWidth || $height < $maxHeight) return ; switch ($type) { case 1: $img = imagecreatefromgif($srcImage); break; case 2: $img = imagecreatefromjpeg($srcImage); break; case 3: $img = imagecreatefrompng($srcImage); break; } $scale = min($maxWidth/$width, $maxHeight/$height); //求出綻放比例 if($scale < 1) { $newWidth = floor($scale*$width); $newHeight = floor($scale*$height); $newImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $newName = ""; $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile); switch($type) { case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality)) return "$newName.gif"; break; case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality)) return "$newName.png"; break; default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; } imagedestroy($newImg); } imagedestroy($img); return false; }其中 $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);具體目的是什麼?
回複內容:
function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100) { list($width, $height, $type, $attr) = getimagesize($srcImage); if($width < $maxWidth || $height < $maxHeight) return ; switch ($type) { case 1: $img = imagecreatefromgif($srcImage); break; case 2: $img = imagecreatefromjpeg($srcImage); break; case 3: $img = imagecreatefrompng($srcImage); break; } $scale = min($maxWidth/$width, $maxHeight/$height); //求出綻放比例 if($scale < 1) { $newWidth = floor($scale*$width); $newHeight = floor($scale*$height); $newImg = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $newName = ""; $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile); switch($type) { case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality)) return "$newName.gif"; break; case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality)) return "$newName.png"; break; default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality)) return "$newName.jpg"; break; } imagedestroy($newImg); } imagedestroy($img); return false; }其中 $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);具體目的是什麼?
因為tofile($srcImage,$toFile)第二個參數$toFile自己指定的話存在格式問題,比如srcImage是jpg,但是如果你填寫的toFile是png,那格式就對不上了,因此如果你制定了toFile的檔案尾碼,那就直接幹掉,然後在直接將原圖片的格式追加在你指定的toFile後面。
--
簡單來說:
tofile('a.jpg','b.png');
最終產生的是b.jpg而不是b.png