Resize Images on the fly


/ Published in: PHP
Save to your folder(s)

Creating thumbnails of the images is required many a times, this code will be useful to know about the logic of thumbnail generation.


Copy this code and paste it in your HTML
  1. /**********************
  2. *@filename - path to the image
  3. *@tmpname - temporary path to thumbnail
  4. *@xmax - max width
  5. *@ymax - max height
  6. */
  7. function resize_image($filename, $tmpname, $xmax, $ymax)
  8. {
  9. $ext = explode(".", $filename);
  10. $ext = $ext[count($ext)-1];
  11.  
  12. if($ext == "jpg" || $ext == "jpeg")
  13. $im = imagecreatefromjpeg($tmpname);
  14. elseif($ext == "png")
  15. $im = imagecreatefrompng($tmpname);
  16. elseif($ext == "gif")
  17. $im = imagecreatefromgif($tmpname);
  18.  
  19. $x = imagesx($im);
  20. $y = imagesy($im);
  21.  
  22. if($x <= $xmax && $y <= $ymax)
  23. return $im;
  24.  
  25. if($x >= $y) {
  26. $newx = $xmax;
  27. $newy = $newx * $y / $x;
  28. }
  29. else {
  30. $newy = $ymax;
  31. $newx = $x / $y * $newy;
  32. }
  33.  
  34. $im2 = imagecreatetruecolor($newx, $newy);
  35. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
  36. return $im2;
  37. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.