php等比例生成缩略图程序

这个程序很实用,但只是用来生成等比例生成缩略图,你要把文件上传到服务器,然后再由此函数来操作,有需要的朋友参考一下.

php等比例生成缩略图程序代码如下:

  1. function reSizeImg($imgSrc, $resize_width, $resize_height, $isCut=false) {
  2. //图片的类型
  3. $type = substr ( strrchr ( $imgSrc, "." ), 1 );
  4. //初始化图象
  5. if ($type == "jpg") {
  6. $im = imagecreatefromjpeg ( $imgSrc );
  7. }
  8. if ($type == "gif") {
  9. $im = imagecreatefromgif ( $imgSrc );
  10. }
  11. if ($type == "png") {
  12. $im = imagecreatefrompng ( $imgSrc );
  13. }
  14. //目标图象地址
  15. $full_length = strlen ( $imgSrc );
  16. $type_length = strlen ( $type );
  17. $name_length = $full_length - $type_length;
  18. $name = substr ( $imgSrc, 0, $name_length - 1 );
  19. $dstimg = $name . "_s." . $type;
  20. $width = imagesx ( $im );
  21. $height = imagesy ( $im );
  22. //生成图象
  23. //改变后的图象的比例
  24. $resize_ratio = ($resize_width) / ($resize_height);
  25. //实际图象的比例
  26. $ratio = ($width) / ($height);
  27. if (($isCut) == 1) //裁图
  28. {
  29. if ($ratio >= $resize_ratio) //高度优先
  30. {
  31. $newimg = imagecreatetruecolor ( $resize_width, $resize_height );
  32. imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, (($height) * $resize_ratio), $height );
  33. ImageJpeg ( $newimg, $dstimg );
  34. }
  35. if ($ratio < $resize_ratio) //宽度优先
  36. {
  37. $newimg = imagecreatetruecolor ( $resize_width, $resize_height );
  38. imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, $resize_height, $width, (($width) / $resize_ratio) );
  39. ImageJpeg ( $newimg, $dstimg );
  40. }
  41. } else //不裁图
  42. {//开源代码phpfensi.com
  43. if ($ratio >= $resize_ratio) {
  44. $newimg = imagecreatetruecolor ( $resize_width, ($resize_width) / $ratio );
  45. imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, $resize_width, ($resize_width) / $ratio, $width, $height );
  46. ImageJpeg ( $newimg, $dstimg );
  47. }
  48. if ($ratio < $resize_ratio) {
  49. $newimg = imagecreatetruecolor ( ($resize_height) * $ratio, $resize_height );
  50. imagecopyresampled ( $newimg, $im, 0, 0, 0, 0, ($resize_height) * $ratio, $resize_height, $width, $height );
  51. ImageJpeg ( $newimg, $dstimg );
  52. }
  53. }
  54. ImageDestroy ( $im );
  55. }

调用方法简单,直接reSizeImg就可以了,参考很简单.