php按指定大小等比缩放生成上传图片缩略图

  1. /**
  2. * *
  3. *等比缩放
  4. * @param unknown_type $srcImage 源图片路径
  5. * @param unknown_type $toFile 目标图片路径
  6. * @param unknown_type $maxWidth 最大宽
  7. * @param unknown_type $maxHeight 最大高
  8. * @param unknown_type $imgQuality 图片质量
  9. * @return unknown
  10. */
  11. function resize($srcImage,$toFile,$maxWidth = 100,$maxHeight = 100,$imgQuality=100)
  12. {
  13. list($width, $height, $type, $attr) = getimagesize($srcImage);
  14. if($width < $maxWidth || $height < $maxHeight) return ;
  15. switch ($type) {
  16. case 1: $img = imagecreatefromgif($srcImage); break;
  17. case 2: $img = imagecreatefromjpeg($srcImage); break;
  18. case 3: $img = imagecreatefrompng($srcImage); break;
  19. }
  20. $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例
  21. if($scale < 1) {
  22. $newWidth = floor($scale*$width);
  23. $newHeight = floor($scale*$height);
  24. $newImg = imagecreatetruecolor($newWidth, $newHeight);
  25. imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  26. $newName = "";
  27. $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);
  28. switch($type) {
  29. case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))
  30. return "$newName.gif"; break;
  31. case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
  32. return "$newName.jpg"; break;
  33. case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))
  34. return "$newName.png"; break;
  35. default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))//开源代码phpfensi.com
  36. return "$newName.jpg"; break;
  37. }
  38. imagedestroy($newImg);
  39. }
  40. imagedestroy($img);
  41. return false;
  42. }