Image resizer (thumbnail generator)


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

If the optional parameter $crop is set to TRUE the image will be zoomed and cropped to specific size ($new_size). Else, the image will be resized to size, keeping aspect ratio and using $new_size as max size.


Copy this code and paste it in your HTML
  1. function image_resize($input_file, $output_file, $new_size=75, $crop=true) {
  2. if(!file_exists($input_file)) {
  3. return false;
  4. }
  5. if (function_exists('ini_set')) {
  6. @ini_set('memory_limit', -1);
  7. ini_set( 'arg_separator.output' , '&' );
  8. }
  9. if(eregi('\.jpg$|\.jpeg$', $input_file)) {
  10. $original = @imagecreatefromjpeg($input_file);
  11. }
  12. elseif (eregi('\.gif$', $input_file)) {
  13. $original = @imagecreatefromgif($input_file);
  14. }
  15. elseif (eregi('\.png$', $input_file)) {
  16. $original = @imagecreatefrompng($input_file);
  17. }
  18. else {
  19. return false;
  20. }
  21. if ($original) {
  22. if (function_exists('getimagesize')) {
  23. list($width, $height, $type, $attr) = getimagesize($input_file);
  24. } else {
  25. return false;
  26. }
  27. $ratio['x'] = round($width/$new_size, 2);
  28. $ratio['y'] = round($height/$new_size, 2);
  29. if($crop == true) {
  30. $ratio = min($ratio['x'], $ratio['y']);
  31. }
  32. else {
  33. $ratio = max($ratio['x'], $ratio['y']);
  34. }
  35. $smallheight = floor($height / $ratio);
  36. $smallwidth = floor($width / $ratio);
  37. if($crop == true) {
  38. $ofx = floor(($new_size - $smallwidth) / 2);
  39. $ofy = floor(($new_size - $smallheight) / 2);
  40. }
  41. else {
  42. $ofx = $ofy = 0;
  43. }
  44.  
  45. if (function_exists('imagecreatetruecolor')) {
  46. if($crop == true) {
  47. $small = imagecreatetruecolor($new_size, $new_size);
  48. }
  49. else {
  50. $small = imagecreatetruecolor($smallwidth, $smallheight);
  51. }
  52. } else {
  53. if($crop == true) {
  54. $small = imagecreate($new_size, $new_size);
  55. }
  56. else {
  57. $small = imagecreate($smallwidth, $smallheight);
  58. }
  59. }
  60. if (function_exists('imagecopyresampled')) {
  61. imagecopyresampled($small, $original, $ofx, $ofy, 0, 0, $smallwidth, $smallheight, $width, $height);
  62. } else {
  63. imagecopyresized($small, $original, $ofx, $ofy, 0, 0, $smallwidth, $smallheight, $width, $height);
  64. }
  65. if(imagejpeg($small, $output_file)) {
  66. if(file_exists($output_file)) {
  67. return true;
  68. }
  69. }
  70. else {
  71. return false;
  72. }
  73. }
  74. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.