php生成缩略图代码

  1. <?php
  2. /**
  3. * 生成缩略图
  4. * $srcName----为原图片路径
  5. * $newWidth,$newHeight----分别缩略图的最大宽,高
  6. * $newName----为缩略图文件名(含路径),默认为加入thumbnail
  7. * @param string $srcName
  8. * @param int $newWidth
  9. * @param int $newHeight
  10. * @param string $newName
  11. * return viod
  12. */
  13. function resizeImg($srcName,$newWidth,$newHeight,$newName="")
  14. {
  15. if($newName=="")
  16. {
  17. $nameArr=explode('.',$srcName);
  18. $expName=array_pop($nameArr);
  19. $expName='thumbnail.'.$expName;
  20. array_push($nameArr,$expName);
  21. $newName = implode('.',$nameArr);
  22. }
  23. $info = "";
  24. $data = getimagesize($srcName,$info);
  25. switch ($data[2])
  26. {
  27. case 1:
  28. if(!function_exists("imagecreatefromgif")){
  29. echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!返回";
  30. exit();
  31. }
  32. $im = ImageCreateFromGIF($srcName);
  33. break;
  34. case 2:
  35. if(!function_exists("imagecreatefromjpeg")){
  36. echo "你的GD库不能使用jpeg格式的图片,请使用其它格式的图片!返回";
  37. exit();
  38. }
  39. $im = ImageCreateFromJpeg($srcName);
  40. break;
  41. case 3:
  42. $im = ImageCreateFromPNG($srcName);
  43. break;
  44. }
  45. $srcW=ImageSX($im);
  46. $srcH=ImageSY($im);
  47. $newWidthH=$newWidth/$newHeight;
  48. $srcWH=$srcW/$srcH;
  49. if($newWidthH<=$srcWH){
  50. $ftoW=$newWidth;
  51. $ftoH=$ftoW*($srcH/$srcW);
  52. }
  53. else{
  54. $ftoH=$newHeight;
  55. $ftoW=$ftoH*($srcW/$srcH);
  56. }
  57. if($srcW>$newWidth||$srcH>$newHeight)
  58. {
  59. if(function_exists("imagecreatetruecolor"))
  60. {
  61. @$ni = ImageCreateTrueColor($ftoW,$ftoH);
  62. if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  63. else
  64. {
  65. $ni=ImageCreate($ftoW,$ftoH);
  66. ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  67. }
  68. }
  69. else
  70. {
  71. $ni=ImageCreate($ftoW,$ftoH);
  72. ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  73. }
  74. if(function_exists('imagejpeg')) ImageJpeg($ni,$newName);
  75. else ImagePNG($ni,$newName);
  76. ImageDestroy($ni);
  77. }
  78. ImageDestroy($im);
  79. }
  80. //开源代码phpfensi.com
  81. resizeImg('123.JPG',150,150);
  82. ?>