Home  >  Article  >  Backend Development  >  A function that creates image thumbnails

A function that creates image thumbnails

WBOY
WBOYOriginal
2016-07-25 09:07:14939browse
  1. /**

  2. * Create image thumbnail, return true if successful
  3. *
  4. * @param string $cat directory
  5. * @param string $oldname original image file name
  6. * @param string $newname new image file name
  7. * @param int $width abbreviation Thumbnail width
  8. * @param int $height Thumbnail height
  9. * @return
  10. */
  11. function thumb($cat,$oldname,$newname,$width=160,$height=120){
  12. $srcFile = $cat. "/" .$oldname;
  13. $data = getimagesize($srcFile);
  14. $dscFile = $cat. "/". $newname;

  15. switch ($data[2]) {

  16. case 1:
  17. $im = imagecreatefromgif($srcFile);
  18. break;

  19. case 2:

  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. if(($srcW/$width)>=($srcH/$height)){

  29. $temp_height=$height;
  30. $temp_width=$srcW/($srcH/$height);
  31. $src_X=abs(($width-$temp_width)/2);
  32. $src_Y=0;
  33. }
  34. else{
  35. $temp_width=$width;
  36. $temp_height=$srcH/($srcW/$width);
  37. $src_X=0;
  38. $src_Y=abs(($height-$temp_height)/2);
  39. }

  40. $temp_img=imagecreatetruecolor($temp_width,$temp_height);

  41. imagecopyresized($temp_img,$im,0,0,0,0,$temp_width,$temp_height,$srcW,$srcH);

  42. $ni=imagecreatetruecolor($width,$height);

  43. imagecopyresized($ni,$temp_img,0,0,$src_X,$src_Y,$width,$height,$width,$height);
  44. $cr = imagejpeg($ni,$dscFile);

  45. if ($cr){

  46. chmod($dscFile, 0777);
  47. return true;
  48. }
  49. }
  50. ?>

复制代码



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