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 2 3 4 5 8
  1. Hello,

    I use this below to get a random image on my website.
    Can I include the Image resizer in this, and if so how do I do this?
    I’m definetely not an expert….

    Thanks,
    Mark

    and on the location of the image:

    <?php
    $image = getRandomImage(‘somedir’);

    echo “”;

    ?>

  2. Sorry, the above is not the full script I use for the random image, this is it:
    Thanks,
    Mark

    and the location of the image:

    <?php
    $image = getRandomImage(‘somedir’);

    echo “”;

    ?>

  3. @Joe

    Thanks for the help. It looks like my host sucks. I don’t have permission to use chgrp via ssh or inside a php script. Should that be an issue for my host or is it unreasonable? What is your host? Thanks!

  4.  
  5. @Chris: I use MediaTemple for hosting. One of the things that I like about MT is that I have SSH access and can do a lot of things in the shell that are more difficult to do in other ways. Here’s some more technical information about Shifting Pixel if you care to know more.

    As for your issue, I would think that it should be a pretty reasonable thing to do on a web host. You should ask your host what you need to do to make a directory writable by the web server (but not the world) and hopefully they will be able to point you in the right direction.

  6. Excellent tool to use

  7. I don’t know if i was the only one who has had this problem but i was having problems getting gif images to work until i added the quality line around line 260. I just copied
    $quality= round(10 – ($quality / 10)); // PNG needs a compression level of 0 (no compression) through 9 and put it with the gif case too. I don’t know if that makes sense or if it’s even a bug.

    Thanks for this script!

    Brandon

  8. @BandonRandon

    Good catch – I posted that fix a few weeks ago on here, but it’s apparently gone unnoticed by the author. I would consider this a bug for sure. Hopefully it gets put in the next release. Still, this is indeed a very nice script.

  9. This is really great !

    I integrated it in CMS Made Simple, and it’s just what was missing.

    Thanks alot !!!

  10. Hi
    I m not getting the resized image neither do i get error for view image all i get is alt text of IMG tag..
    i have at root image.php,dir imagecache & testimg.php
    please can anyone help me out

  11. I got it!!!
    i think php version /gd may have issue it ran on php version 5 earlier i was testing on php 4
    i still dont know what was error earlier…

  12. manojkumar said

    HI guys,

    I had a need like this,
    While uploading a regular image – i need to convert that image into 6 different sizes and should be stored into folders.

    The resizing must/should be done only while uploading the images.

    Does this script will do my need.

    if not please send me some url’s or code for this.

    Regards,
    manoj

  13. Well, I can do the same by writing a custom script in GD. But surely this will save time.

    Thanks man!

  14. Hi,
    I may be totally stupid, but let me ask. My web server is php 5.2.6.
    I unziped the file on my web server.
    I created a directory called “imagecache”
    I made my imagecache directory is writable (chmod 775)
    I used your sample
    I save it as page.php and uploaded.
    But only A Coffee Bean 1 appear on my screen. Could you tell me what I am doing wrong please?

  15. I have a high traffic site. Does anyone try this script on heavy traffic? I tried phpthumb and others scripts like this one, but there are to slow for me. I recently found one that makes chaching on database (mysql), but this is still slow for me. Any suggestions?

  16. Wonderful tool! What will be better is to add positioning when image is cropped (eg, when cropping a very long image, you can choose to grab the part starting from y=100px)

  17. thanks for this script – really use full
    Ive also added in eTags for faster broser delivery

    eg;

    $eTag = ‘”‘.md5($thumbModified).’”‘;
    header(‘ETag: ‘.$eTag);

    (where every you are setting successfull header info)

  18. Ok guys, thanks for all of the good feedback and bug reports. I just uploaded version 1.4 which should address the GIF quality bug and the missing ETag headers.

  19. I dunno if it’s so smart, if you can’t resize up. ;)

  20. I notice that you have the script working with wordpress, how did you manage to do this? Anyone else know How I could get this into the img tag in wordpress?

    Thanks

  21. All that comes up for me is the alt. The image doesn’t appear. I followed the code sample exactly. I created the empty ‘imagecache’ folder as well. Here is my img tag:

    “”

    In this case, all that comes up is ‘this is an image’.

    What could be wrong? Thanks to however helps..

  22. Ah, the comment system messed up my img tag: here is the src and alt inside the img tag:

    src=”/image.php/image.jpg?width=100&height=100&image=image.jpg” alt=”this is an image”

    anyone know what could be wrong?

  23. Great php script. thanks for sharing with us

  24. this is a great script: the comments are great too, a lot of nice suggestions.

    mine will be: how to make this script able to resize external images on the fly i.e. images referenced using http://google.com/image.jpg etc?

  25. Michael Rubens said

    I’ve been looking for a viable alternative to PHPthumb. I’d love to be able to use your script but I, for the life of me, can’t seem to get it to function.

    image.php installed in ROOT directory /var/www/vhosts/mysite.com/httpdocs along with imagecache directory. The tag is calling an image from my upload /images/uploads/ directory

    http://72.47.207.116/image.php/2007_HW.jpg?width=332&height=212&cropratio=1:1image=/images/uploads/2007_HW.jpg

    All I get is an error: Error: no image was specified – except for the fact that the image does exist

    http://72.47.207.116/images/uploads/2007_HW.jpg.

    What am I missing?

  26. @Michael Rubens: It looks like you forgot an ampersand before your image parameter. Try this link:

    http://72.47.207.116/image.php/2007_HW.jpg?width=332&height=212&cropratio=1:1&image=/images/uploads/2007_HW.jpg

    That takes care of the error, but it doesn’t generate an image for some reason. I’m not really sure why. You could try turning on error reporting and see if anything comes up. At the beginning of image.php, just add

    error_reporting(E_ALL);
  27. Michael Rubens said

    @ Joe: got the missing & corrected, thanks for spotting that.

    I’ve tried this on 2 different hosting environments. A shared host (PHP version 4.4.6) and my VPS with MT (PHP version 4.3.9).

    You don’t state a minimum version for either PHP or GD but in both cases everything is installed.

    With error messages enabled I get no errors on my VPS and on the shared account I get Fatal error: Call to undefined function: imageconvolution() in /home/fashiond/public_html/image.php on line 324

    Any ideas?

  28. @Michael: Ah ha! It looks like that is the function that I use for sharpening and it is only available in PHP 5.1.0+ (http://us2.php.net/manual/en/function.imageconvolution.php).

    If you want to try and make it work, you can try to remove the code that does the sharpening… shouldn’t be too hard if you have a little PHP knowledge.

  29. @Michael: I don’t know if this will work for you, but on the (gs) accounts with MT it is possible to turn on different versions of PHP if you want to use PHP 5. Here’s a link to one of their KnowledgeBase articles that tell you how to do that.

    And here’s one that walks you through upgrading PHP on MT’s (dv) 3.0

    Hopefully that’s helpful!

  30. Michael Rubens said

    @Joe, Thanks…I thought this might be the issue. Thanks for the resource links. I’m actually looking at upgrading my dv account from 3.0 to 3.5 which will also address this issue, and a few others as well.

    But this clears up my confusion.

    Thanks

  31. Does anyone know whats wrong with mine? I really need help, thanks.

  32. @Scummy: A lot of things could be going wrong. You really need to post more information. Here are some tips (all of which have been covered in the comments already):

    • Try visiting the URL that you are using in your SRC tag directly in the browser. If there is an error message, 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–I’ll take a look at it and tell you if anything looks out of the ordinary.
  33. Joe mentioned this to me in an email and it worked!

    http://localhost/project/image.php/image.jpg?width=100&height=100&image=/project/image.jpg

    so the src would be

    src=”/project/image.php/image.jpg?width=100&height=100&image=/project/image.jpg”

    @Joe: Thanks! =D

  34. There is no need to host CPU-intensive thumbnailing scripts like this on your webserver anymore. Instead, you can use a specialized service for remote, on-demand image manipulation like SteadyOffload.

    All you have to do is use a custom HTML attribute called “xmanip” with the img tag. This will deliver the thumbnail from one of the globally scattered cache servers:

    <img srcx=”image.jpg” xmanip=”RescaleWidth 130″ />

    So much easier than all the hassle with GD or ImageMagick! Moreover, this reduces the CPU load of your webserver and saves some bandwidth.

  35. I could not get the code to work until i applied the solutions from both Parker Jackson & Michael Rubens.
    I had changed the refererence to $_SERVER['DOCUMENT_ROOT']
    to the absolute path as Parker suggested with no results but then
    I noticed that my servers used the exact same absolute path as described by Michael and so I also changed the link to include the complete URL in the img src tag.
    These two solutions together solved the problem
    THANKS

  36. [...] Smart Image Resizer [...]

  37. @Joe Lencioni: Thanks a lot for simple and efficient script, outstanding!

    @Jean-Marie and all the others, whose found sharpening algorithm little bit aggressive: I’ve added another parameter – ‘slevel’ [slevel (optional, 0-10, default: 8) sharpening level, 0 = no sharpening, 10 = max. sharpness)]. It softenes a bit the result sharpness of thumbnail.

    Download sLevel version: http://www.sunnysites.cz/temp/Image-Resizer-with-sLevel-1.4.zip

  38. [...] 3, 2008 — released Smart Image Resizer the jawsome PHP script that powers the image resizing on this [...]

  39. I seem to be having a problem where the script is not scaling an image up. I read through the code and i notice that the script exits when the specified dimensions are greater than the original (the problem I am having). Can this script scale an image up?

    Thanks,

    PS – Great script.

  40. @Nemesis: It isn’t designed to scale images up, but it shouldn’t be too difficult to accomplish that with some tweaking.

  41. Hi – I am having a problem with the following line:

    $lastModifiedString = gmdate(‘D, d M Y H:i:s’, $lastModified) . ‘ GMT’;

    The error logs show that $lastModified is undefined.

    Thanks

  42. @Tim: Thanks for the report. I’ll have a look at it. Any chance you can tell me the line number?

  43. Ok, I made some changes and uploaded 1.4.1. The problem should be fixed now. @Tim–can you confirm? Thanks again for the report.

  44. hello,

    I love the script, going to be using it in an upcoming application. I’ve also decided to extended in a little bit by adding a “maxsize” parameter.

    Since I’m not sure if the image I’m showing will be in Landscape or Portrait, what I wanted to do is check the height/width to determine this, then set the “maxHeight” for a portrait image to the “maxSize” value, then set the “maxWidth” of that same image to “999999…” (what you currently have for really big).

    Here’s the code I added… hopefully this will come thru ok in the post. If not, you can email me and I’ll give you my modified image.php (v1.4)

    
    /////////////////////
    // PARAMETERS
    /////////////////////
    ...
    // maxsize		maximum size that either height or width can be.
    ...
    
    $maxWidth		= (isset($_GET['width'])) ? (int) $_GET['width'] : 0;
    $maxHeight		= (isset($_GET['height'])) ? (int) $_GET['height'] : 0;
    $maxSize		= (isset($_GET['maxsize'])) ? (int) $_GET['maxsize'] : 0;
    ...
    
    elseif ($maxWidth && !$maxHeight)
    {
    	$maxHeight	= 99999999999999;
    }
    elseif($maxSize && !$maxWidth && !$maxHeight)
    {
    	if($width < $height){
    		$maxWidth = $maxSize;
    		$maxHeight	= 99999999999999;
    	} else {
    		$maxHeight = $maxSize;
    		$maxWidth	= 99999999999999;
    	}
    }...
    
  45. Very Nice. This is something that I was dearly looking for and now you have helped me. Great post. Now I can resize my images much more effectively.

  46. [...] Smart image resizer es un script PHP que nos permite de manera muy sencilla redimensionar y cortar imagenes y esto sin modificar la imagen original. Obviamente esta funcionalidad la proporciona usando la libreria GD para graficos. [...]

  47. Great concept! I think you have solved my image resizing woes. =)

  48. [...] conhecia o phpThumb() e hoje soube do Smart Image Resizer, ambos geradores de thumbs em PHP. Se o primeiro é mais antigo e reputado, o segundo tem a [...]

  49. Hi, this looks like a great utility. Are you aware of any gui manipulative tools so that I can allow the end client to set the crop manually.
    I would like the client to be able to set the crop area, to a specific ratio, and then let this script automagically take care of the resize/thumbnails.
    I would store the settings in a file and generate the relevant img urls with php.
    Thanks

  50. Any chance of a Progressive option to output progressive jpegs?

  51. [...] URL: http://shiftingpixel.com/2008/03/03/smart-image-resizer/ [...]

 
1 2 3 4 5 8