« »

On-The-Fly Dynamic Thumbnails with PHP

thumbs_up.jpg
I hate thumbnails. There. I’ve said it. Well… I suppose hate is a strong word… but I seriously strongly dislike them. I guess it’s not the thumbnails themselves I hate… it’s the extra work involved. Open up the image, crop, resize, save, upload, not right? rinse, lather, repeat until right.

To save myself the time (and sanity), I compiled this script… (I say compiled because it uses bits and pieces of other scripts i’ve seen over the past few years, with my own changes and additions) that dynamically creates a thumbnail. The script is called as follows:

  1.  
  2.   <img src=‘/dfn_thumbnailer.php&img=/images/my_images.jpg&mw=150&mh=150′ />
  3.  

What the script does is take three $_GET arguments, img, mw, and mh, and returns a jpeg image. The main difference between this script and the others I’ve found online is that it doesn’t just resize the image, it resamples it. This makes a world of difference, as simply resized images will appear pixelated.

  1.  
  2. <?
  3. # ———————————————————————-
  4. # DFN Thumbnailer
  5. # http://www.digifuzz.net
  6. # digifuzz@gmail.com
  7. # ———————————————————————-
  8.  
  9. # Constants
  10. $IMAGE_BASE = "http://your.base.url.here";
  11.  
  12. $image_file = $_GET[‘img’];
  13. $MAX_WIDTH  = $_GET[‘mw’];
  14. $MAX_HEIGHT = $_GET[‘mh’];
  15. global $img;
  16.  
  17. # No Image?  No go.
  18. if( !$image_file || $image_file == "" )
  19. {
  20.       die( "NO FILE FOUND.");
  21. }      
  22.  
  23. # if no max width is set, set one.
  24. if( !$MAX_WIDTH || $MAX_WIDTH == "" )
  25. {
  26.   $MAX_WIDTH="150";
  27. }      
  28.  
  29. # if not max height is set, set one.
  30. if( !$MAX_HEIGHT || $MAX_HEIGHT == "" )
  31. {
  32.   $MAX_HEIGHT="150";
  33. }      
  34.  
  35. # Get image location
  36. $image_path = $IMAGE_BASE . $image_file;
  37.  
  38. # Load image
  39. $img = null;
  40. $ext = strtolower(end(explode(‘.’, $image_path)));
  41. if ($ext == ‘jpg’ || $ext == ‘jpeg’)
  42. {
  43.     $img = @imagecreatefromjpeg($image_path);
  44. }
  45. else if ($ext == ‘png’)
  46. {
  47.   $img = @imagecreatefrompng($image_path);
  48. }
  49. else if ($ext == ‘gif’)
  50. {
  51.   # Only if your version of GD includes GIF support
  52.   $img = @imagecreatefromgif($image_path);
  53. }
  54.  
  55. # If an image was successfully loaded, test the image for size
  56. if ($img)
  57. {
  58.   # Get image size and scale ratio
  59.   $width = imagesx($img);
  60.   $height = imagesy($img);
  61.   $scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height);
  62.  
  63.   # If the image is larger than the max shrink it
  64.   if ($scale < 1)
  65.   {
  66.     $new_width = floor($scale*$width);
  67.     $new_height = floor($scale*$height);
  68.  
  69.     # Create a new temporary image
  70.     $tmp_img = imagecreatetruecolor($new_width, $new_height);
  71.  
  72.     # Copy and resize old image into new image
  73.     imagecopyresampled($tmp_img, $img, 0, 0, 0, 0,
  74.  
  75.     $new_width, $new_height, $width, $height);
  76.     imagedestroy($img);
  77.     $img = $tmp_img;        
  78.   }    
  79. }
  80.  
  81. # Create error image if necessary
  82. if (!$img)
  83. {
  84.   $img = imagecreate($MAX_WIDTH, $MAX_HEIGHT);
  85.   imagecolorallocate($img,255,255,255);
  86.   $c = imagecolorallocate($img,255,0,0);
  87.   imageline($img,0,0,$MAX_WIDTH,$MAX_HEIGHT,$c2);
  88.   imageline($img,$MAX_WIDTH,0,0,$MAX_HEIGHT,$c2);
  89. }
  90.  
  91. # Display the image
  92. header("Content-type: image/jpeg");
  93. imagejpeg($img,,500);
  94. ?>
  95.  

This script is a real time saver on my end. It saves me from having to write a bunch more code, and handle more file-uploads for my clients. For example, I recently implemented this script for a client who runs an online shoe store. Rather than having to upload 3 different images for every shoe (and get the image sizes right), he just uploads one. Doesn’t matter what size it is, because it will be resized and resampled to fit on the fly. Saves on disk space too.

A few final words about the script – if you can’t already tell just by looking at the source. It accepts jpegs, gifs, and pngs. If you don’t set a max width and a max height, one will be set automagically. The image will be scaled to within the set dimensions, but the aspect ratio will be kept intact.

Happy coding!

digifuzz.

  • Share/Bookmark

Posted on Friday, June 13th, 2008 at 8:43 am and is filed under Php. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

11 Responses to “On-The-Fly Dynamic Thumbnails with PHP”

  1. 1

    Personally, to avoid the whole extension matching thing, I would use the following:

    $img = @imagecreatefromstring(file_get_contents($image_path));

    It will automagically detect what type of image it is, from any of JPEG, PNG, GIF, WBMP, and GD2.

  2. 2

    Nice!

    To be safe / prevent root path disclosure, you might put intval around the mw and mh variables before using them, and using a file_exists on the file

  3. 3

    Hey,

    This is brilliant.
    Thanks a lot.

  4. 4

    I understand the script, but I’m not understanding how to use it. Too new to Apache and too used to ASP.Net, I reckon. I don’t really know how to find the problem.

    The script runs without errors, but using an image link as described in the example link, above, I don’t seem to be passing any parameters and get the “FILE NOT FOUND” message (I’m apparently not passing the image_width and _height parameters, also; slight changes to die without a width or height shows they aren’t being passsed to dfn_thumbnailer, too.

    But when I hard-code the image name in the thumbnailer script, I get a text-view version of the page for output.

    If you would not mind, could you give a bit more detail about how this is used for the stone dumb like me?

    Thanks.

  5. 5

    doesnt work with filenames with spaces… its not 1990 anymore yo!

  6. 6

    LOL, great site looking through many things you have published. Just a little lost on how this is working.

    I tried as directions show but a little messed up on base url and image url setup.

    whether the $IMAGE_BASE is the site url or the site url with /images/ tagged on it. is there a zip working of this that I can download

    thanks.

    Mark.

  7. 7

    I can’t get this to work at all. Anyone got it working?

  8. 8

    Essentially, you call it like this:


    < img src="/thumbnailer.php?img=/site_images/image.jpg&height=300&width=300" />

    does that make sense?

    And the BASE URL is just what it sounds like, what its set to depends on how you wish to use it. If all your image files will forever be located in http://www.yoursite.com/site_images/ then that would be your BASE URL and you could call it like: src=”/thumbnailer.php?img=image.jpg&height=300&width=300″. Otherwise, if you will vary where the image is coming from, then you can just specify your BASE URL to be http://www.yoursite.com and call it as shown in my first example.

    Good luck.

  9. 9

    Hi, it works very well, but you have a typo error over here:

    imageline($img,0,0,$MAX_WIDTH,$MAX_HEIGHT,$c2);
    imageline($img,$MAX_WIDTH,0,0,$MAX_HEIGHT,$c2);

    The variable $c2 doesn’t exists, it should be $c

    Best regards from Colombia-SouthAmerica

  10. 10

    Not my cup of tea but it

  11. 11

    Hi, It doesn’t seem to work for me. I get no errors, it just displays nothing. I am dropping the following code in to my html:

    Thats correct right?

    Thanks

    Chris

Leave a Reply