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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<?php # ---------------------------------------------------------------------- # 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 29 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
bro its not showing thumbnail for png images, how i can do this ?
kaleem – Change this:
if ($ext == ‘jpg’ || $ext == ‘jpeg’)
to this:
if ($ext == ‘jpg’ || $ext == ‘jpeg’ || $ext == ‘png’)
@PHIL Bro its not working although i have made changes according to your instructions.
please 1st you test this script for png images then tell me.
NOTE=== not working for png images 🙁
OK, I’ve fixed everything mentioned above and I still can’t get it to work. It looks like it’s not running from the <img src="thumbs.php?… line. Also, I'm a little confused at the at the bottom. Shouldn’t these be <?php tabs? What do those two things mean?
Any help appreciated…
I fixed the way the code was displaying — look again and see if it makes a difference.
Thanks, got it working!!
BTW, in Netbeans 7.1 IDE, the <img src=program.php construct does NOT work. When I moved the code to the actual web server, it worked like a charm!
I have been using your script for years but I have a new VPS and it just wont work on the VPE. I get this error
Strict Standards: Only variables should be passed by reference in /home/bayph1/public_html/dfn_thumbnailer.php on line 43
Warning: Cannot modify header information – headers already sent by (output started at /home/bayph1/public_html/dfn_thumbnailer.php:43) in /home/bayph1/public_html/dfn_thumbnailer.php on line 91
Warning: imagejpeg(): Filename cannot be empty in /home/bayph1/public_html/dfn_thumbnailer.php on line 92
If I stop error messages it still doesnt work. I have the GD selected.
I seems like its something to do with the headers as when I strip out all the code it starts saying things like theres errors with the image and white spaces etc. (I have tried multiple images) But the code works fine on my reseller acconuts. Its not even the php version as they are pretty much the same.
Wondered if you had any ideas?
Bob – please paste in line 43 from your script file so we can get a better idea of what exactly is causing the issue. I don’t think it’s a header thing, that header error is just caused by the fact that there are other errors mucking up the output.
-Phil
Best explanation ever, you sure know what you’re talking about
thank you – very intresting for me.
please paste in line 43 from your script file so we can get a better idea of what exactly is causing the issue. I don’t think it’s a header thing, that header error is just caused by the fact that there are other errors mucking up the output.
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.