A ridiculously easy-to-use PHP script for resizing images the smart way.

One of the challenges that comes with maintaining a graphic-intensive website like Shifting Pixel is finding a way to get high quality images throughout the site with as little effort as possible. To tackle this, I developed the Smart Image Resizer and have been using it around the site for the past few months. I couldn’t be happier.

The major advantage of this script is that it allows me to resize and crop any image on my website without touching the actual image or writing any code. I upload each image once at a high enough resolution and can then reuse it at any size I want, anywhere I want. It doesn’t matter if the images are in a post, on a page, or in a template file–it just works. All of the magic is done through the query string part of the URL in the src attribute of the img tag.

And, if this wasn’t a big enough time-saver for me right now, it’ll be a huge time-saver the next time I decide to redesign my site. It’s a relief that I won’t have to go through to resize and re-upload a thousand photos to make sure they look right–I’ll just have to change the links to them and I’ll be all set.

Features

  • Resizes JPEGs, GIFs, and PNGs
  • Intelligently sharpens for crisp photos at any size
  • Can crop based on width:height ratios
  • Can color-fill transparent GIFs and PNGs
  • Built-in caching keeps image variations for optimal performance

Requirements

PHP 5.1.0+ compiled with GD. (You need a version of GD that supports imageconvolution(), such as the bundled version. Note that on some distributions, the default php-gd package may not be adequate.)

Download

Download SLIR 2.0

Download Smart Image Resizer v1.4.1 (Released August 6, 2008)

Tip jar

[flattr /]

To Install

  1. Unzip on your web server
  2. In the same directory, create a directory called “imagecache”
  3. Make your imagecache directory is writable by the web server (usually chmod 775)

Troubleshooting

  • Turn on “display_errors = on” in your php.ini file. Restart Apache and verify with a phpinfo().
  • Try visiting the URL that you are using as the src attribute of your img tag directly in the browser. For example, for example, stick this in your browser’s address bar: http://example.com/image.php?width=180&height=180&image=/path/to/image.jpg. If there is an error message here, it should be quite helpful.
  • If that doesn’t give you any information, turn on error reporting (add error_reporting(E_ALL); to the top of image.php) and see if that gives you any information. It is possible that the script is trying to use a function that doesn’t exist in your installation and configuration of PHP.
  • If you can’t get the script to give you any information, try peaking into your error logs.
  • Finally, if you can’t get any information out of any of these things, run a phpinfo() and send me a link–if I have time I’ll take a look at it and tell you if anything looks out of the ordinary. As of this time, I am spending more time focusing on SLIR 2.

Common error messages

Fatal error: Call to undefined function imagecreatetruecolor()
This most likely means that you do not have GD installed. To fix this, install GD (make sure you are using a version that includes the imageconvolution() function).
Fatal error: Call to undefined function imageconvolution()
This means that you are using a version of GD that does not include the imageconvolution() function. To fix this, you will either need to find a repository that includes the version of GD that you need, or compile php-gd from source.

License

I love to hear when my work is being used, so if you decide to use it, feel encouraged to send me an email. Smart Image Resizer is released under a Creative Commons Attribution-Share Alike 3.0 United States license. All I ask is that you include a link back to Shifting Pixel (either this page or shiftingpixel.com), but don’t worry about including a big link on each page if you don’t want to–one will do just nicely. Feel free to contact me to discuss any specifics.

Examples

These examples use my photo of this coffee bean. For more fine photography, browse my “Must See” photos or subscribe.

Resizing a JPEG

<img src="/image.php?width=200&amp;height=200&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" /> 

Coffee Bean Coffee Bean Coffee Bean

Resizing and cropping a JPEG into a square

<img src="/image.php?width=150&amp;height=150&amp;cropratio=1:1&amp;image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" /> 

Coffee Bean Coffee Bean Coffee Bean


371 Comments

 
1 3 4 5 6 7 8
  1. @dan That’s a good idea, I hadn’t even considered progressive JPEGs. One thing to keep in mind though is that progressive JPEGs can’t be used in Flash.

    As far as I can tell from the documentation, what you are trying should work. Perhaps SIR is serving up a cached non-progressive version? Try adding ‘&nocache’ to the end of your request.

  2. Hi!

    Just included this great script on my frontpage… work great for the articles that is scaled to be in two columns!

    I was just wondering if the script clears the cache after a while. If not, is it possible to make a script that checks for images older than a given date and deletes them?

  3. @HovardK I’m glad you like it. :) No, it does not clear old files out of the cache. Yes, it is possible to make a script that deletes old files. You would probably want to set up a cron job to do that. Here’s some information on deleting files older than x days in Linux.

  4.  
  5. Great Script! I was able to quickly modify it to work within the scope of my project.

    The quality of the images looks great, it just works. Again great job!

  6. This is a totally awesome script. I’m wondering, is it possible to somehow modify it to display watermarks on the fly?

  7. @Mike Yes, it is certainly possible.

  8. This was a real treat, heh, I’ve been traversing all over to find a good fix for my new site galleries. Oh yes, this was a christmasgift aaight.

    btw, I got to dissagree hard on the comment to add a readme.txt to the deal.
    That file would’ve been deleted before I even thought of reading it, besides… now I know the documentation is safe.

    Works out of the box if one actually takes time to _READ_ the f**** comments in the .php file.

  9. [...] http://shiftingpixel.com/2008/03/03/smart-image-resizer/ You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed. [...]

  10. Hi Blogger,

    The script is really amazing. Keep it up :-)

  11. Hi ,This is really nice script and easy to integrate with any system.
    and

    1.Is it possible to use water mark with this script?

  12. [...] Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel Resize images locally on your server no more need to manually update and resize images. (tags: image webdesign webdevelopment php css programming script gd) [...]

  13. Here is a small tip on using this amazing script.

    I was trying to do a FIXED sized thumbnail but it wasn’t a square one. The cool thing is that since it calculates the cropratio mathematically, you can call the script using other numbers besides 3:2, 1:1, etc.

    For example, I’m using 4:5 width=160 height=200 forcing the images to be resized to this non-regular size.

  14. nayana adassuriya said

    great work

  15. Error if Webserver is IIS!

    The image.php/abc.jpg?width=xxx mean that file not exists :(

    It maybe understand image.php is a directory, not a script!

    Can you see this problem?

  16. Wondering if you have any plans to add a function like phpThumbs “Zoom Crop” method.

    This functionality has proven invaluable when there is no way to dictate the source dimensions. You can output to a set size and the script will take the source, size it down, and crop accordingly without adjusting the image proportions.

    Maybe I’m missing something but I’ve not been able to reproduce the Image Resizer script.

  17. I’m curious if what I want to accomplish is possible with your script. If I set it up to crop to a ratio of 3:4 – width=”360″, height =”525″ using

    where test.jpg is 1280px × 1019px. The resulting thumb is ends up being 360px × 480px, not 360px x 525px.

    Is there a way to ensure that, regardless of the source image’s dimensions (assuming it is bigger than the desired image size), the resulting image is the exact dimensions I want?

    A live example can be seen here: http://www.shirtfight.com/home/test/

  18. oops…looks like the example code didn’t show up, this is what I’m using:

  19. Hi

    I am osCommerce developer.
    I need to resize image in size (KB) not width and height of image.

    Suppose any image uploaded with size more then 200KB then I need to reduce it to nearer to 200KB.

    Will this script do like this?

    Thanks
    osCommerce Addon Installation

  20. @osCommerce Addon Installation: physical file size is determined by the image’s quality. The script does allow you to change the quality.

    I’m looking for a way to generate watermarks in real time. I posted a comment earlier asking about it and was told it is possible, but I still can’t figure it out yet. Anyone has any insight on this? Thanks!

  21. I have a script that dinamically generate images from a database. So how can I use smart image resize for images that have an url like /myscript.php?id=n ?

  22. I’ll definitely try this out. Looks very useful,
    but I have my doubts on the load time of a page
    when you try to load in about a hundred images at a time.

  23. This might just be the most useful script I’ve used so far.
    I’ve had some trouble getting it to work, but then I saw an
    error in your examples.

    the “;” should be replaced by a “&”

  24. This a message for Ray (message dated 26th june 2008).
    I would really like to know how you integrate this to cms made simple… if ever you read this or if anyone know how to do this, i would really appreciate some help ;)

  25. Hi team,

    Please help me, i tried the code but its not working. please send me an example with images. is it work in Oscommerce site?

    Please help me its bit urgent.

    am waiting for your reply

    Thanks
    RMajeed

  26. Well I’ve got a demo of this script om my blog:

    http://steven.webfizz.be/

    you can download it from there

  27. Hello, I didn’t have time to check all the comments and all the scripts, but I’ve seen how the php script is called (img html tag).
    QUESTION:
    Couldn’t someone abuse the script and call the image in the browser with different sizes, untill it fills up the disk (theoretically) and increases the load ???

  28. the script works when i tested in Localhost, but when i upload it to godaddy web hosting it dosent work. plz help

    read write permission given to the folder imagecache..

    Error message when image src attribute pasted in browser : -

    Parse error: syntax error, unexpected ‘$’ in /home/content/m/e/e/meedhooadmin/html/football.jpg on line 54

    php info . http://meedhoodevelopment.com/info.php

  29. @Amin, it seems to be working just fine to me: http://meedhoodevelopment.com/image.php?width=100&image=/football.jpg

  30. it works now.. :D
    in my code after image.php(i wrote the image name) that must be the problem.. but in localhost i works like that too.. any was thank u so much.. and this a very nice script ..

  31. Hi Steven,

    Thanks, its working fine. Thanks a lot for the great script.

    RMajeed

  32. Hi:
    I belong to an art assoc. that uses CMS Made simple. There is a sharpness problem with both the thumbnail and the double clicked enlarged image.

    Would I be able to use one of your programs…such as Smart Image to sharpen existing images?

    I am not a programmer but was given the task of instructing artists on how to resize their photos to suit the site dimensions.

    Thanks.

  33. @Brian Seed: Smart Image Resizer will automatically sharpen JPEG files after it resizes them.

    Also, I am nearly ready to release a beta version of 2.0, so keep your eyes peeled for that.

  34. Hi!

    I put this code into the start of the image.php:

    < ?php
    $files = glob('imagecache/*', GLOB_BRACE);
    usort($files, 'filemtime_compare');
    
    function filemtime_compare($a, $b)
    {
    	return filemtime($a) - filemtime($b);
    }
    
    $i = 0;
    $show = 1000;
    
    $today = mktime(date('h,i,s,m,d,Y'));
    $onemonth = $today-47645;
    
    foreach($files as $file)
    {
    	if($i == $show) break; else ++$i;
    	$fileunixtime = filemtime($file);
    
    	if ($fileunixtime <= $onemonth)
    	{
    		unlink($file);
    	}
    }
    ?>

    This clears files older than 24 hours… I use the script on a site featuring over 150 bands, with bandpictures shown in various places and sizes… Lots of traffic also, so it is good to get rid of cache daily. Not sure how good this solution is, but it works and I have not noticed any delays on the site…

    Maybe this tip could come in handy for someone?

    There might also be an idea to set the count down to “10″ instead of 1000, to make it clear out little by little…
    :)

  35. Hi,

    I’m using smart image in my web application, but none of the functionality seems to be working. I’ve done all the error checking you’ve suggested and got no errors. Also, the path to the image is good (even with the smart image src attribute). However, when I run gd_info(); I get no response. Does it seem likely that my image would display, but with none of smart image’s effects if gd isn’t installed on my server? I use Bluehost, for reference. Thanks.

  36. First of all i thank You for your code because i have applied successfully in my project and it works.I got an appriciation in my company because we used to face this image distortion problem for a long time but i have tried and successfully applied.Thank you so much

  37. If you are feeling brave, I just uploaded the first beta of SLIR (Smart Lencioni Image Resizer) 2.0.

    There are still some more things that I would like to do before I finalize the 2.0 release, but I have been using it for a while and it seems to be pretty stable where I have used it–so I’d say it is pretty safe. I would really appreciate it if some of you could test it out and let me know what you think or if you find any bugs.

    http://code.google.com/p/smart-lencioni-image-resizer/

  38. Hi,

    I have been using a similar kind of script for long on my projects. And I think, this kind of dynamic image resizing scripts makes the website a bit slow.

    So it is better to use, a thumbnail generation script that creates thumbnail right at the moment you upload the image through your website back-end. And on the front end (on actual website) the website page is much faster as it just needs to download the thumbnail and does not run the script for each image on the page.

  39. @ michael rubens:
    where test.jpg is 1280px × 1019px. The resulting thumb is ends up being 360px × 480px, not 360px x 525px.

    Is there a way to ensure that, regardless of the source image’s dimensions (assuming it is bigger than the desired image size), the resulting image is the exact dimensions I want?

    for your case, try using the following parameter:

    width=360&height=9999&cropratio=360:525

    works for me.

  40. Hi,

    I’m going to look into this, but I’m wondering if I should hold out till v2 is finished… Do you have a planned release date for the finished version? Also, I see you’re up to r11, but only r1 can be downloaded?

    Cheers

  41. @Marc: If you are planning on a big implementation of this, it might be worthwhile waiting for 2.0. You could certainly use 2.0b1 but things are going to be different in the final 2.0 release.

    Regarding the r1 and r11 question, the “r” numbers correspond to the revision numbers in the subversion repository. 2.0b1 is not r1. If you would like to download the latest (potentially unstable) version, feel free to check it out from the subversion repository.

    As for a release date, it’s hard to say exactly when things will be ready. Hopefully I will be able to get 2.0b2 out soon and we’ll go from there.

    If you do end up using the beta and have any feedback, positive or negative, please let me know.

  42. Thanks man,

    I was searching for a good image resizing script like this.
    I am saying thanks once again.

  43. [...] 19. Smart Image Resizer [...]

  44. this is rad. i’ve been searching around for a good image resizer for a while, found one that just resized, but no caching, so no point really, but this one rocks my world, thanks alot bro… i’ll throw you credit in the code if i use it on a project.

  45. Thanks alot, This script is such a fantastic & useful piece, it has saved me alot of time and coding, I am using it on all my sites now.

    Thank you very much again! =)

  46. [...] 19. Smart Image Resizer [...]

  47. Great script! Smooth, easy and fantastic result!

    It seems that in order to generate a cached version of the image you will have to visit each image. It is possible to generate the cached version of all the pictures in one go?

    Then I could clear the imagecache folder once in a will and generate a new set of cached images.

  48. PavanPuligandla said

    can anyone please help me out, how to use this script..
    secondly i’m getting images from MYSQL which were shown in a “Smarty template” file, the image tag is :

    In the above image tag {$special_offers[i][2]} is not a static image, so how can you add resize to these dynamic images? can you please reply me with proper image resize tag in my scenario..
    please respond me..

  49. Joe Lencioni said

    @R.B.: You might just want to set up a cron job to periodically delete old files from the cache. Then you don’t have to worry about re-building the entire cache in one go.

    @PavanPuligandla: If there is no actual image file, the script will tell you that the image file cannot be found. You will either have to export the images from your MySQL database to image files first, or you will have to tweak the script to work with images in your database.

  50. [...] 19. Smart Image Resizer [...]

  51. [...] 19. Smart Image Resizer [...]

 
1 3 4 5 6 7 8