On-The-Fly Dynamic Thumbnails with PHP
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 |
<img alt="" src="/dfn_thumbnailer.php&img=/images/my_images.jpg&mw=150&mh=150" /> |
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 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<!--? # ---------------------------------------------------------------------- # DFN Thumbnailer # http://www.digifuzz.net # digifuzz@gmail.com # ---------------------------------------------------------------------- # Constants $IMAGE_BASE = "http://your.base.url.here"; $image_file = $_GET['img']; $MAX_WIDTH = $_GET['mw']; $MAX_HEIGHT = $_GET['mh']; global $img; # No Image? No go. if( !$image_file || $image_file == "" ) { die( "NO FILE FOUND."); } # if no max width is set, set one. if( !$MAX_WIDTH || $MAX_WIDTH == "" ) { $MAX_WIDTH="150"; } # if not max height is set, set one. if( !$MAX_HEIGHT || $MAX_HEIGHT == "" ) { $MAX_HEIGHT="150"; } # Get image location $image_path = $IMAGE_BASE . $image_file; # Load image $img = null; $ext = strtolower(end(explode('.', $image_path))); if ($ext == 'jpg' || $ext == 'jpeg') { $img = @imagecreatefromjpeg($image_path); } else if ($ext == 'png') { $img = @imagecreatefrompng($image_path); } else if ($ext == 'gif') { # Only if your version of GD includes GIF support $img = @imagecreatefromgif($image_path); } # If an image was successfully loaded, test the image for size if ($img) { # Get image size and scale ratio $width = imagesx($img); $height = imagesy($img); $scale = min($MAX_WIDTH/$width, $MAX_HEIGHT/$height); # If the image is larger than the max shrink it if ($scale < 1) { $new_width = floor($scale*$width); $new_height = floor($scale*$height); # Create a new temporary image $tmp_img = imagecreatetruecolor($new_width, $new_height); # Copy and resize old image into new image imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($img); $img = $tmp_img; } } # Create error image if necessary if (!$img) { $img = imagecreate($MAX_WIDTH, $MAX_HEIGHT); imagecolorallocate($img,255,255,255); $c = imagecolorallocate($img,255,0,0); imageline($img,0,0,$MAX_WIDTH,$MAX_HEIGHT,$c2); imageline($img,$MAX_WIDTH,0,0,$MAX_HEIGHT,$c2); } # Display the image header("Content-type: image/jpeg"); imagejpeg($img,'',500); ?--> |
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.
There are 19 comments.
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.
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
Hey,
This is brilliant.
Thanks a lot.
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.
doesnt work with filenames with spaces… its not 1990 anymore yo!
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.
I can’t get this to work at all. Anyone got it working?
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.
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
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
John,
in order your code to work
the link is wrong: replave the first “&” with a “?”
there’s another error pointed by latinosoft: replace $c2 with $c
add a “/” on $IMAGE_BASE
and replace this line:
$ext = strtolower(end(explode(‘.’, $image_path)));
with
$ext = pathinfo($image_path, PATHINFO_EXTENSION);
additionally, try the suggestion by cody j.
—
done, it works great
@Just a Friend: Looks like I got caught by the cut-and-paste bug. I took this from something I put together for one of my clients, and while rewriting it to be standalone, I missed a few things
Thanks for pointing them out, corrections will be made.
Very useful script, thanks!
A note for others who may have problems using it:
Make sure you replace all non standard quotes in the script such as ’ with ‘ and so on.
And for replace .php& with .php?
OK, my comment converted the single quote to slanted quote. Just make sure to convert slanted quotes to normal quotes when copying script.
Hey Guys, I have this error…
PHP Warning: imagejpeg(/uploads): failed to open stream: Permission denied on this line
imagejpeg($img,”,500);
Is there a quotes typo?
@tXBOY:
Change
imagejpeg($img,”,500);
to
imagejpeg($img,”,500);
is there anyway to write or save the thumbnail to a folder on the server instead of just displaying it?
Thanks
I noticed everyone was having a problem with the way the syntax-highlighter code was changing single-quotes to fancy-schmancy single-quotes and causing errors. I have switched to a new, more robust syntax-highlighter which should resolve any cut & paste issues you may have had!
Cheers
Hi there,
Thanks for the excellent script. Quick question, do you know what in your script is causing me to be unable to output “thumbs” (really just slightly downsized images) over 1000px wide?
For some reason, even if both limits are set to, say 2700 px, the image comes out 1000 wide (and I’m assuming it would be 1000 tall if it was a “vertically aligned” image).
Thanks for any ideas!
-Phil
By submitting a comment you grant digifuzz.net a perpetual license to reproduce your words and name/web site in attribution. Inappropriate and irrelevant comments will be removed at an admin’s discretion. Your email is used for verification purposes only, it will never be shared.