PHP Re-size Image


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

Can't seem to remember where I found this and it's no longer in my bookmarks. If you know where this came from please provide the link so credit can go to the right person.


Copy this code and paste it in your HTML
  1. <?php
  2. function resize_image($img, $thumb_width, $newfilename) {
  3. $max_width=$thumb_width;
  4. //Check if GD extension is loaded
  5. if (!extension_loaded('gd') && !extension_loaded('gd2')) {
  6. trigger_error("GD is not loaded", E_USER_WARNING);
  7. return false;
  8. }
  9. //Get Image size info
  10. list($width_orig, $height_orig, $image_type) = getimagesize($img);
  11. switch ($image_type) {
  12. case 1: $im = imagecreatefromgif($img); break;
  13. case 2: $im = imagecreatefromjpeg($img); break;
  14. case 3: $im = imagecreatefrompng($img); break;
  15. default: trigger_error('Unsupported filetype!', E_USER_WARNING); break;
  16. }
  17. /*** calculate the aspect ratio ***/
  18. $aspect_ratio = (float) $height_orig / $width_orig;
  19. /*** calulate the thumbnail width based on the height ***/
  20. $thumb_width = $max_width;
  21. $thumb_height = round($thumb_width * $aspect_ratio);
  22. //while($thumb_height>$max_width) {
  23. // $thumb_width-=10;
  24. // $thumb_height = round($thumb_width * $aspect_ratio);
  25. // }
  26. $newImg = imagecreatetruecolor($thumb_width, $thumb_height);
  27. /* Check if this image is PNG or GIF, then set if Transparent*/
  28. if(($image_type == 1) || ($image_type==3)) {
  29. imagealphablending($newImg, false);
  30. imagesavealpha($newImg,true);
  31. $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  32. imagefilledrectangle($newImg, 0, 0, $thumb_width, $thumb_height, $transparent);
  33. }
  34. imagecopyresampled($newImg, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
  35. //Generate the file, and rename it to $newfilenamea
  36. switch ($image_type) {
  37. case 1: imagegif($newImg,$newfilename); break;
  38. case 2: imagejpeg($newImg,$newfilename); break;
  39. case 3: imagepng($newImg,$newfilename); break;
  40. default: trigger_error('Failed resize image!', E_USER_WARNING); break;
  41. }
  42. return $newfilename;
  43. }
  44. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.