欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php等比缩放上传图片缩略图的代码

程序员文章站 2022-06-16 09:56:57
...
  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 switch ($type) {
  15. case 1: $img = imagecreatefromgif($srcImage); break;
  16. case 2: $img = imagecreatefromjpeg($srcImage); break;
  17. case 3: $img = imagecreatefrompng($srcImage); break;
  18. }
  19. $scale = min($maxWidth/$width, $maxHeight/$height); //求出绽放比例
  20. if($scale $newWidth = floor($scale*$width);
  21. $newHeight = floor($scale*$height);
  22. $newImg = imagecreatetruecolor($newWidth, $newHeight);
  23. imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  24. $newName = "";
  25. $toFile = preg_replace("/(.gif|.jpg|.jpeg|.png)/i","",$toFile);
  26. switch($type) {
  27. case 1: if(imagegif($newImg, "$toFile$newName.gif", $imgQuality))
  28. return "$newName.gif"; break;
  29. case 2: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
  30. return "$newName.jpg"; break;
  31. case 3: if(imagepng($newImg, "$toFile$newName.png", $imgQuality))
  32. return "$newName.png"; break;
  33. default: if(imagejpeg($newImg, "$toFile$newName.jpg", $imgQuality))
  34. return "$newName.jpg"; break;
  35. }
  36. imagedestroy($newImg);
  37. }
  38. imagedestroy($img);
  39. return false;
  40. }
复制代码