简单的PHP生成缩略图函数

原创
2016-07-25 08:48:02 661浏览
简单的生成缩略图函数,支持图片格式:gif、jpeg、png和bmp,支持缩放到固定大小或进行等比缩放,支持直接输入到浏览器或保存到文件。
  1. /**
  2. * 简单的生成缩略图函数(支持图片格式:gif、jpeg、png和bmp)
  3. * @author xiaoshuoit@163.com
  4. * @param string $src 源图片路径
  5. * @param int $width 缩略图宽度(只指定高度时进行等比缩放)
  6. * @param int $width 缩略图高度(只指定宽度时进行等比缩放)
  7. * @param string $filename 保存路径(不指定时直接输出到浏览器)
  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');
复制代码


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:百度Sitemap 实时推送代码 下一条:邮箱激活

相关文章

查看更多