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 6 8
  1. [...] Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel John   Comment RSS « PatternCooler | Seamless Background Designs for Blogs, Mobile Phone Wallpapers, MySpace, Webdesign Projects [...]

  2. [...] aí a dica: Smart Image Resizer PHP: a simple way to create thumbnails and more on the fly — Shifting Pixel. Posted in PHP | Tags: blog, e-comerce, hotsite, orkut, PHP, resize, resizer, rss, script, tag [...]

  3. [...] Страничка проекта: http://shiftingpixel.com/2008/03/03/smart-image-resizer/ [...]

  4.  
  5. It would be cool if you added a cache time.

    For example in my case, I show webcam images from other sites on my web page (with permisssion ofcorse). If your script has a cache time, I could store the webcam images locally on my webserver, and not unneccesary stress the webcam owners webserver :)

  6. @zk: I don’t know of anything off the top of my head. It shouldn’t be too difficult to whip something up in PHP though.

    @Dan: Good suggestion. I will have to look into that.

    @Uyyrr: Also a good suggestion. Thanks!

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

  8. Just FYI, in your usage example, the “&image=” parameter renders for me as:

    ℑ=

    Which i though must have been “I=”, and then realised there should be an ampersand before it (“&I=”). My images weren’t working, so I had to digg a little further to realise that the parameter should actually be:

    &image=

    You might want to update the code in the example, as it seems incorrect and a little confusing.

    Thanks for a great app!

  9. @Adam: Thanks for pointing that out. I just upgraded WordPress today and it must have eaten some of my code. Oh well, it’s fixed now. :)

  10. [...] 3, 2008 &mdas­h­; r­e­le­as­e­d Smar­t­ I­mage R­esi­z­er­ t­h­e­ jawso­­me­ PH­P sc­r­ipt­ [...]

  11. Like it, very nice, Thanks

  12. [...] Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel [...]

  13. Fistly, Joe, this is a great script that I have been using and following since its release. I have found it especially useful when developing online stores for clients who have little or no knowledge of how to crop images properly. With this script I can have them upload their original image and the necessary crops are automated by the script. Brilliant.

    However, I have found two bugs that aren’t specific to any version but rather the environments they run on it would appear. I have developed sites across numerous versions of PHP and Apache, but I have recently come across two bugs that I can’t seem to resolve.

    Firstly, including “&image=/myimage.jpg” breaks the script. It simply returns the “no image specified” error. Removing the “&” and replacing it with a simple “&” gets it working again, but destroys XHTML validity. This is true when the URL is included within HTML and pasted directly into the browser.

    Secondly, and most annoyingly, it would appear that including the “cropratio” parameter breaks the script in some environments. Oddly, however, if the URL is pasted directly into the browser the image appears as expected. It only breaks when the parameter is added to URLs inside HTML.

    I plan on looking into a mod_rewrite to counter both these bugs at some point, but I thought they were worth pointing out.

    Thanks again.

    Adam M

  14. Sorry, I made a small mistake in my comment above..

    The second sentence of the third paragraph should read:

    “Removing the “&” and replacing it with a simple “&” gets it working again, but destroys XHTML validity”.

  15. Oddly, however, if the URL is pasted directly into the browser the image appears as expected. It only breaks when the parameter is added to URLs inside HTML.

    That makes me wonder if it might be a browser issue. It is very odd. I’d like to know if you can figure out what is happening here.

  16. Joe, for the time being I have got past these issues with a mod_rewrite rule to change how the script is called.

    I am now accessing the images with:

    http://www.domain.com/image/250/250/1:1/image.jpg

    With the rewrite rule:

    RewriteRule ^image/([0-9]+)/([0-9]+)/([0-9]+):([0-9]+)/(.*).(gif|jpg|png)$ image.php/$5?width=$1&height=$2&cropratio=$3:$4&image=/imagestore/$5.$6 [L]

    I’m not a mod_rewrite expert by any means so this rule may not be perfect, but it does add security in terms of only allowing numbers for the width, height and cropratio parameters, and only processing the rule if the specified image is .gif, .jpg or .png. The rule also allows the user to download the image with its original filename, which I know you were very keen to keep intact.

    I am still having trouble using “& amp;” [the space is present so that the comment system doesn't strip it down to use an "&" like my previous comments] for the image parameter. However, not using “& amp;” for the other parameters breaks when using the colon in the URL for the cropratio. I confirmed this by substituting the colon for a hyphen inside the URL and script.

    Moreover, for my solution all my images are stored in one directory so this works fine for me, but may not be portable to solutions where the directory of images changes frequently. I’m sure all it would take would be a simply rewrite rule change, or perhaps some minor tweaking of the code, but I currently don’t have to worry about it.

    Now that I have this solution in place it is more than likely that I will include this in all further site developments that use this great script. However, I will strive to dig in to the code when I can to see if I can work out why exactly the issues I mentioned break the script in particular circumstances.

  17. In regards to the problem with ampersands, the separator can be changed from ampersands to a different symbol such as a semicolon (;), as recommended by the World Wide Web Consortium.


    will allow the PHP script to accept “;” as an argument separator, changing the URL’s to a form such as:

    The semicolon need not be escaped in XHTML.

    I haven’t actually tested this, since I’m not a user of this script, but I thought that I’d offer a possible solution to the ampersand issue.

  18. [...] Today I finally finished up with the member photo section thanks to a handy little script I found here. I wanted to do all the coding myself, but this was exactly what I needed, so why re-invent the [...]

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

  20. [...] Smart Image Resizer [...]

  21. Resize or Crop your WordPress post level images with customizable size using Joe Lencioni’s Smart Image Resizer…

    If you use WordPress and you are blogging about something which requires a personalized image for every post such as Gadget blogs or you want to use different images for every post you have for illustration purpose only like what we commonly found on t…

  22. [...] Smart image resizer is a PHP script which makes it very easy to resize & crop images. And, this is done without touching the original image. [...]

  23. thanks for that great script :)

    i had the same error like Michael Rubens although i have i have PHP Version 5.2.0-8 installed.

    commenting out line 324 has fixed the problem. thanks

  24. requirem: Thank you for that. I recently changed server setup and this image script stopped working. I couldn’t figure out the problem until I read some of the comments here. I have PHP Version 5.2.0-8 also.

  25. I LOVE this script. Thanks for the hard work on it.

    One thing tho…Can it be modified to use an image rendered by another php script? That is, setting the image path to a php file? I use another script sometimes, rotator.php, that will randomly select an image from a folder. It’d be cool if I could use this script to resize an image that was randomly chosen by that other script.

  26. “content aware resizing” is in the next version of photoshop.

    http://sippey.typepad.com/filtered/2008/10/newsrooms-and-photoshop-content-scaling.html

    any chance it’ll find its way into SIR any time soon?

    there has been a demo of this amazing technology on youTube for quite some time:

    http://www.youtube.com/watch?v=vIFCV2spKtg

    i don’t think adobe owns the idea…

  27. @dan That’s a great idea, thanks for the suggestion! I would love to add seam carving to SIR, but I can’t say if or when I will be able to–it seems like a pretty complex process. In the meantime, it looks like seam carving is available in ImageMagick v6 if you are eager to do some seam carving on your pages.

  28. Thanks for the reply and suggestion re: seam carving. On second thought, this would probably bloat the script and take it off-course from its original mission.

    Unrelated question:

    I’m using a PHP slideshow to crossfade between photos that are being output by SIR. Under certain circumstances, I get an “image not found” icon in place of some of the images. In those situations, I attempt to open the broken image in a new window in order to sanity check the URL… and the image appears fine. If I reload the page, it seems to work fine. Purge the cache, retry… and problem is back.

    I am using cropratio and & in place of ampersands… from this thread it seems that might be part of the problem? At least in terms of the problem disappearing when the image URL is opened in a new browser window (where & would have been replaced with & by the browser). In which case, the aforementioned mod_rewrite might fix the problem by eliminating the need for & in my URLs.

    But now I wonder whether the culprit is the fact that another PHP script is involved. Then again, the script is merely crossfading between DIVs, not actually processing any of the content (images, labels., etc) contained within them. The url to the script is here:

    http://www.brandspankingnew.net/specials/crossfader/bsn.Crossfader.html

    Any suggestions? Anyone else see this problem? Seems related to other complaints in this thread but I’d like more insight, both for myself and to bulletproof this otherwise STELLAR utility.

  29. @dan: Any chance you can send me a link to your problematic implementation of the crossfader?

  30. I am using this script with success on my website, but I have one area where I am running into problems. Users can log into their account and upload photos using an upload script. The resulting image link looks like this:

    http://10.0.1.10/talent_images/get.php?id=316c2a82d81688401957b585fab895be&name=DSCN1141.jpg

    When using the SIR script I get a link that looks like this:

    http://10.0.1.10/image.php/DSCN1141.jpg?width=275&height=350&image=/talent_images/get.php?id=316c2a82d81688401957b585fab895be&name=DSCN1141.jpg

    Which returns an error message that looks like this:

    Error: image does not exist: /Library/WebServer/Documents/talent_images/get.php?id=316c2a82d81688401957b585fab895be

    I’m guessing that the problem is that last “&name=…” gets removed by the SIR script. Is there anyway to resolve this issue. Thanks

  31. @phcranston: it looks like you are using SIR to resize an image that is returned by a different PHP script. Wher SIR fires up, it checks for a physical file in the path that is specified and if that file does not exist, then it stops and outputs that error message. If the file does exist, it opens it and reads the data in directly from the file system, so unfortunately I don’t believe SIR will work in the way you are trying to use it. It’s an interesting use that I hadn’t thought of. If you feel like tweaking the code, I bet you could get around this current limitation using something like cURL.

  32. @Joe: Thanks for the feedback. Tried figuring out the cURL thing this afternoon but my php skills aren’t up to that level. I’ll have to come up with some else.

  33. Can it take all pics from dir and resize them to size I want and replace original?

  34. @Web News: that is contrary to the purpose of this script.

  35. Does this script do anti-aliasing?
    I mean, if I reduce an image to 50%, it softens jagged lines in a white image with back text?
    Thank you and keep up the good work!!

  36. I am VERY excited about the prospect of this script. I haven’t gotten it to work yet, but I think that is because I’m not placing things correctly. I’m a bit of a tweaker, so my knowledge is still in beginning stages.

    I’m using this for a wordpress site and I’m not sure I’m putting the imagecache directory in the best place.

    I also want to make sure I’m calling the image correctly. Does any one have a sample of a full line they could share?

    I appreciate the mentoring!
    .

  37. Great Script! Keep up the good work!

    Is there a way to make the background of an image transparent(or with different colour) while resizing?

  38. thank you

  39. Hello Mr. Lencioni! Compliments for this nice script. I have used this for a image-hosting service.
    Good work.
    PS: Excuse me for my bad English, but I’m Italian.

    Bye!

  40. Lloyd Taylor said

    Great script, but I can’t get it to work.

    Can anyone help?

    I get the error:

    Warning: Cannot modify header information – headers already sent by (output started at /home/ccastle/public_html/image.php:2) in /home/castle/public_html/image.php on line 384

  41. I i want to used this script during the upload of my pictures, currently i need to upload four pics at the same time with other details such as username,etc

    than i have to put the NAME only into the database, there must be two pictures in the folder
    main image: image333.jpg
    thumbnail: thimage333.jpg

    how can i do this please help

  42. I use it and it very use full, thanks Joe much!

  43. Hi there!
    This is very interesting…
    I’m working on a flashgallery & wonder if this would work with flash as well.
    Flash doesn’t use the img tag unless it’s an image that is inside a textfield.

    Niklas

  44. @Niklas: Yes, I believe it will work with Flash.

  45. Hey Joe
    Thanks a mill.. this works just amazingly well.

    On a sidenote regarding FLASH …
    Images imported via an XML file (The XML file holds the image src) into FLASH dont show up in Opera 9.6 and IE6. Works fine in all other browsers.

  46. You save my life man!
    Incredible script!

  47. By the way, it seems that if the image url contains a tilde (~) then this script will fail…

  48. HI all is it possible to run this image resizer on server which has this warning? :

    Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/root/images/fotogaleria/IMGP1480.JPG) is not within the allowed path(s): (.:/home/ic/:/home/free/:/disk1/home/ic/:/disk1/home/free/:/tmp:/usr/share/php/:/usr/share/fpdf/:/usr/share/fonts/:/usr/share/php/jpgraph/:/usr/share/php/:/var/lib/php5) in /home/free/ic.cz/k/kosenie/root/www/image.php on line 95
    Error: image does not exist: /root/images/fotogaleria/IMGP1480.JPG

    on localhost it works great but at any free web server it doesant :(

  49. [...] проекта: http://shiftingpixel.com/2008/03/03/smart-image-resizer/ Комментариев [...]

  50. mbstring causes horizontal cropping

    I was struggling this weekend with some encoding problems on my mysql/php app and I added this to my php.ini file:


    ;mbstring.language = Neutral ; Set default language to Neutral(UTF-8) (default)
    ;mbstring.internal_encoding = UTF-8 ; Set default internal encoding to UTF-8
    ;mbstring.encoding_translation = On ; HTTP input encoding translation is enabled
    ;mbstring.http_input = auto ; Set HTTP input character set dectection to auto
    ;mbstring.http_output = UTF-8 ; Set HTTP output encoding to UTF-8
    ;mbstring.detect_order = auto ; Set default character encoding detection order to auto
    ;mbstring.substitute_character = none ; Do not print invalid characters

    ;mbstring.func_overload = 7 ; All non-multibyte-safe functions are overloaded with the mbstring alternatives

    Today, Monday, suddenly this script was cutting the lower half of my images off, but keeping the image height normal, and also taking forever to load. I commented out these lines in the php.ini file and that immediately set the resizing script back to working just fine.

    May be a bug or simply my ignorance but I thought this would be good information for everyone using this.

  51. Support for progressive JPEGs would really help with the slow loading of large images.

    Have tried to modify this script myself, without luck. Should be a simple matter of adding this line:

    // turn on progressive jpeg (to do: only do this if outputting jpeg)
    imageinterlace ($dst,1);

    just before this existing line:

    // Write the resized image to the cache
    $outputFunction($dst, $resized, $quality);

    anyway this should work according to:
    http://www.php.net/imageinterlace

    any suggestions?

 
1 2 3 4 5 6 8