Home  >  Article  >  Backend Development  >  PHP code to generate thumbnails (good compatibility)

PHP code to generate thumbnails (good compatibility)

WBOY
WBOYOriginal
2016-07-25 09:11:43786browse

There are many codes for generating thumbnails in PHP, but there are few codes that are fully compatible with gd1.6 and gd2.x and can ensure the clarity of thumbnails. The following code can achieve better compatibility. Share it for everyone to learn and refer to.

  1. function ImageResize($srcFile,$toW,$toH,$toFile="")
  2. {
  3. if($toFile==""){ $toFile = $srcFile; }
  4. $info = "";
  5. $data = GetImageSize($srcFile,$info);
  6. switch ($data[2])
  7. {
  8. case 1:
  9. if(!function_exists("imagecreatefromgif")){
  10. echo "you The GD library cannot use GIF format images, please use Jpeg or PNG format! Return";
  11. exit();
  12. }
  13. $im = ImageCreateFromGIF($srcFile);
  14. break;
  15. case 2:
  16. if(!function_exists("imagecreatefromjpeg")){
  17. echo "Your GD library cannot use images in jpeg format, please use images in other formats!< ;a href='javascript:go(-1);'>Return";
  18. exit();
  19. }
  20. $im = ImageCreateFromJpeg($srcFile);
  21. break;
  22. case 3:
  23. $ im = ImageCreateFromPNG($srcFile);
  24. break;
  25. }
  26. $srcW=ImageSX($im);
  27. $srcH=ImageSY($im);
  28. $toWH=$toW/$toH;
  29. $srcWH=$srcW/ $srcH;
  30. if($toWH<=$srcWH){
  31. $ftoW=$toW;
  32. $ftoH=$ftoW*($srcH/$srcW);
  33. }
  34. else{
  35. $ftoH=$toH;
  36. $ ftoW=$ftoH*($srcW/$srcH);
  37. }
  38. if($srcW>$toW||$srcH>$toH)
  39. {
  40. if(function_exists("imagecreatetruecolor")){
  41. @$ni = ImageCreateTrueColor ($ftoW,$ftoH);
  42. if($ni) ImageCopyResampled($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  43. else{
  44. $ni= ImageCreate($ftoW,$ftoH);
  45. ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  46. }
  47. }else{
  48. $ni=ImageCreate ($ftoW,$ftoH);
  49. ImageCopyResized($ni,$im,0,0,0,0,$ftoW,$ftoH,$srcW,$srcH);
  50. }
  51. if(function_exists('imagejpeg')) ImageJpeg($ni,$toFile);
  52. else ImagePNG($ni,$toFile);
  53. ImageDestroy($ni);
  54. }
  55. ImageDestroy($im);
  56. }
Copy code


Statement:
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