首頁 >後端開發 >php教程 >php使用GD建立保持寬高比的縮圖

php使用GD建立保持寬高比的縮圖

WBOY
WBOY原創
2016-07-25 08:43:07959瀏覽
  1. /**
  2. * Create a thumbnail image from $inputFileName no taller or wider than
  3. * $maxSize. Returns the new image resource or false on error.
  4. * Author: mthorn.net
  5. */
  6. function thumbnail($inputFileName, $maxSize = 100)
  7. {
  8. $info = getimagesize($inputFileName);
  9. $type = isset($info['type']) ? $info['type'] : $info[2];
  10. // Check support of file type
  11. if ( !(imagetypes() & $type) )
  12. {
  13. // Server does not support file type
  14. return false;
  15. }
  16. $width = isset($info['width']) ? $info['width'] : $info[0];
  17. $height = isset($info['height']) ? $info['height'] : $info[1];
  18. // Calculate aspect ratio
  19. $wRatio = $maxSize / $width;
  20. $hRatio = $maxSize / $height;
  21. // Using imagecreatefromstring will automatically detect the file type
  22. $sourceImage = imagecreatefromstring(file_get_contents($inputFileName));
  23. // Calculate a proportional width and height no larger than the max size.
  24. if ( ($width <= $maxSize) && ($height <= $maxSize) )
  25. {
  26. // Input is smaller than thumbnail, do nothing
  27. return $sourceImage;
  28. }
  29. elseif ( ($wRatio * $height) < $maxSize )
  30. {
  31. // Image is horizontal
  32. $tHeight = ceil($wRatio * $height);
  33. $tWidth = $maxSize;
  34. }
  35. else
  36. {
  37. // Image is vertical
  38. $tWidth = ceil($hRatio * $width);
  39. $tHeight = $maxSize;
  40. }
  41. $thumb = imagecreatetruecolor($tWidth, $tHeight);
  42. if ( $sourceImage === false )
  43. {
  44. // Could not load image
  45. return false;
  46. }
  47. // Copy resampled makes a smooth thumbnail
  48. imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $tWidth, $tHeight, $width, $height);
  49. imagedestroy($sourceImage);
  50. return $thumb;
  51. }
  52. /**
  53. * Save the image to a file. Type is determined from the extension.
  54. * $quality is only used for jpegs.
  55. * Author: mthorn.net
  56. */
  57. function imageToFile($im, $fileName, $quality = 80)
  58. {
  59. if ( !$im || file_exists($fileName) )
  60. {
  61. return false;
  62. }
  63. $ext = strtolower(substr($fileName, strrpos($fileName, '.')));
  64. switch ( $ext )
  65. {
  66. case '.gif':
  67. imagegif($im, $fileName);
  68. break;
  69. case '.jpg':
  70. case '.jpeg':
  71. imagejpeg($im, $fileName, $quality);
  72. break;
  73. case '.png':
  74. imagepng($im, $fileName);
  75. break;
  76. case '.bmp':
  77. imagewbmp($im, $fileName);
  78. break;
  79. default:
  80. return false;
  81. }
  82. return true;
  83. }
  84. $im = thumbnail('temp.jpg', 100);
  85. imageToFile($im, 'temp-thumbnail.jpg');
复制代码

php


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn