Home > Backend Development > PHP Tutorial > Simple PHP thumbnail generation function

Simple PHP thumbnail generation function

WBOY
Release: 2016-07-25 08:48:02
Original
1004 people have browsed it
A simple thumbnail generation function supports image formats: gif, jpeg, png and bmp. It supports scaling to a fixed size or proportional scaling. It supports direct input to the browser or saving to a file.
  1. /**
  2. * Simple function to generate thumbnails (supports image formats: gif, jpeg, png and bmp)
  3. * @author xiaoshuoit@163.com
  4. * @param string $src source image path
  5. * @param int $width thumbnail width (Perform proportional scaling when only height is specified)
  6. * @param int $width Thumbnail height (conformal scaling is performed when only width is specified)
  7. * @param string $filename Save path (directly output to the browser when not specified)
  8. * @return bool
  9. */
  10. function simple_thumb($src, $width = null, $height = null, $filename = null) {
  11. if (!isset($width) && !isset($height))
  12. return false;
  13. if (isset($width) && $width <= 0)
  14. return false;
  15. if (isset($height) && $height <= 0)
  16. return false ;
  17. $size = getimagesize($src);
  18. if (!$size)
  19. return false;
  20. list($src_w, $src_h, $src_type) = $size;
  21. $src_mime = $size['mime' ];
  22. switch($src_type) {
  23. case 1 :
  24. $img_type = 'gif';
  25. break;
  26. case 2 :
  27. $img_type = 'jpeg';
  28. break;
  29. case 3 :
  30. $img_type = 'png' ;
  31. break;
  32. case 15 :
  33. $img_type = 'wbmp';
  34. break;
  35. default :
  36. return false;
  37. }
  38. if (!isset($width))
  39. $width = $src_w * ($height / $src_h);
  40. if (!isset($height))
  41. $height = $src_h * ($width / $src_w);
  42. $imagecreatefunc = 'imagecreatefrom' . $img_type;
  43. $src_img = $imagecreatefunc($src );
  44. $dest_img = imagecreatetruecolor($width, $height);
  45. imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
  46. $imagefunc = 'image' . $img_type;
  47. if ($filename) {
  48. $imagefunc($dest_img, $filename);
  49. } else {
  50. header('Content-Type: ' . $src_mime);
  51. $imagefunc($dest_img) ;
  52. }
  53. imagedestroy($src_img);
  54. imagedestroy($dest_img);
  55. return true;
  56. }
  57. simple_thumb("http://www.baidu.com/img/bdlogo.gif", 100);
  58. //simple_thumb("img/example.jpg", 100, null , 'img/example_thumb.jpg');
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template