HELLO
I AM
JOHN

I've been breaking making websites for over 15 years.

On-The-Fly Dynamic Thumbnails with PHP

Posted on June 13, 2008 at 8:43 am

jpgI 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:

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.

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

Written by

John is a web-developer by day, dashing, handsome, and death-defying super-hero by night. Based out of Silver Spring, MD, he does his best to make things do things other than the things they were supposed to on a daily basis, in the process, making the world a better place.

There are 29 comments.

Comment by Cody J.

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.

JUL14 2008 19:57:00
Comment by kguske

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

APR04 2009 19:40:00
Comment by Damin Assad

Hey,

This is brilliant.
Thanks a lot.

MAY14 2009 00:35:00
Comment by K. B. McHugh

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.

JUN17 2009 01:43:00
Comment by m@

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

JUL30 2009 17:06:00
Comment by Mark

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.

SEP20 2009 20:43:00
Comment by Børge Jakobsen

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

OCT06 2009 17:50:00
Comment by digifuzz

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.

OCT09 2009 12:30:00
Comment by Latinosoft

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

NOV01 2009 13:57:00
Comment by Chris

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

MAR07 2010 09:22:00
Comment by just a friend

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

APR23 2012 00:59:00
Comment by digifuzz

@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.

APR23 2012 23:48:00
Comment by Lil

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?

MAY17 2012 15:53:00
Comment by Lil

OK, my comment converted the single quote to slanted quote. Just make sure to convert slanted quotes to normal quotes when copying script.

MAY17 2012 15:55:00
Comment by txboy

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?

JUL17 2012 17:52:00
Comment by Pexsol

@tXBOY:

Change
imagejpeg($img,”,500);

to

imagejpeg($img,”,500);

AUG03 2012 05:51:00
Comment by frazzle

is there anyway to write or save the thumbnail to a folder on the server instead of just displaying it?
Thanks

SEP20 2012 15:12:00
Comment by digifuzz

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

NOV12 2012 12:19:00
Comment by kaleem khan

bro its not showing thumbnail for png images, how i can do this ?

DEC11 2013 03:42:00
Comment by Phil

kaleem – Change this:

if ($ext == ‘jpg’ || $ext == ‘jpeg’)

to this:

if ($ext == ‘jpg’ || $ext == ‘jpeg’ || $ext == ‘png’)

DEC11 2013 21:38:00
Comment by kaleem khan

@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 🙁

DEC12 2013 02:41:00
Comment by Gary B.

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…

APR01 2014 19:42:00
Comment by digifuzz

I fixed the way the code was displaying — look again and see if it makes a difference.

APR02 2014 13:39:00
Comment by Gary B.

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!

APR03 2014 17:51:00
Comment by bob

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?

MAY04 2014 22:29:00
Comment by Phil

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

MAY05 2014 11:27:00
Comment by priligy

Best explanation ever, you sure know what you’re talking about

JUN30 2014 04:45:00
Comment by bestellen

thank you – very intresting for me.

JUN30 2014 11:08:00
Comment by acheter

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.

JUN30 2014 11:11:00

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

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.