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 8
  1. Hello,

    As Bill said, using HTML and CSS for displaying square or rectangular backgrounds is enough. I see no need to inflate this script with that feature. I think future enhancements could be security- or performance-related (but I’m no expert so I won’t suggest anything for this).

    I finally tried this script and I have some remarks:

    1. It seems that the “/coffee-bean.jpg” part of your example (just after “image.php”) is totally useless. Well, at least omitting it altogether didn’t seem to hinder the script. This is good news, because then I can write “/images/sir/image.php?some_parameters&image={path_to_picture}” in my templates, with the bracketed part being replaced by the image path by the template engine. If this “/coffee-bean.jpg” or “/image-name.jpg” you put just after image.php in your examples is just something like eye-candy, I think you should remove it altogether.

    2. Documentation in the php file itself is ok, but a simple readme.txt or howto.txt in your zip file would help many a clueless user. ;)

    3. You write: “If the source image is newer than the cached image or if any of the parameters change (width, height, cropratio, or color), it makes a new one and re-caches it.” I found that changing the “quality” parameter doesn’t make a new image. Moreover, if I first generate and image with quality=10, and then use quality=95, the first generated image has 10 (utterly poor) quality and then the script doesn’t make a new image. I guess a typical real-life scenario would go like this: user asks for a generated image, then wants to try the “quality” parameter because the weight of generated images is a little too high, but nothing changes when he uses that parameter.

    4. Thank you for this script. :)

  2. @Florent V: Thanks for bringing up those points.

    1. I add the “/coffee-bean.jpg” to my example for two reasons. First, if you try to save the file it will save it as this part of the URL instead of as “image.php”. In this respect, it’s just a nice little thing to do for the user. Secondly, (and I don’t have any research to back this up–it’s just my own theory) I think that search engines like Google Image Search might like images that have interesting names more than images called “image.php”.

    2. I agree. :)

    3. Bingo! This is a bug. Apparently, when I added the quality feature, I forgot to add some code to make the caching behave properly. I will try to update this ASAP (probably sometime tonight). Thanks for pointing this out.

    4. You are very welcome. I’m glad you like it.

  3. imageconvolution() does not appear in PHP with non-bundled GD libraries, so i added this after line 63:

    
    //Made by Chao Xu(Mgccl) 2/28/07
    //www.webdevlogs.com
    if(!function_exists('imageconvolution')){
    	function ImageConvolution($src, $filter, $filter_div, $offset){
    	    if ($src==NULL) {
    	        return 0;
    	    }
    
    	    $sx = imagesx($src);
    	    $sy = imagesy($src);
    	    $srcback = ImageCreateTrueColor ($sx, $sy);
    	    ImageAlphaBlending($srcback, false);
    	    ImageAlphaBlending($src, false);
    	    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);
    
    	    if($srcback==NULL){
    	        return 0;
    	    }
    
    	    for ($y=0; $y<$sy; ++$y){
    	        for($x=0; $x> 24);
    
    	            for ($j=0; $j<3; ++$j) {
    	                $yv = min(max($y - 1 + $j, 0), $sy - 1);
    	                for ($i=0; $i> 16) & 0xFF) * $filter[$j][$i];
    	                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
    	                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
    	                    $new_a += ((0x7F000000 & $rgb) >> 24) * $filter[$j][$i];
    	                }
    	            }
    
    	            $new_r = ($new_r/$filter_div)+$offset;
    	            $new_g = ($new_g/$filter_div)+$offset;
    	            $new_b = ($new_b/$filter_div)+$offset;
    	            $new_a = ($new_a/$filter_div)+$offset;
    
    	            $new_r = ($new_r > 255)? 255 : (($new_r  255)? 255 : (($new_g  255)? 255 : (($new_b  127)? 127 : (($new_a = 0) && ($y < $sy)) {
    	                imagesetpixel($src, $x, $y, $new_pxl);
    	            }
    	        }
    	    }
    	    imagedestroy($srcback);
    	    return 1;
    	}
    }
    
  4.  
  5. i am new to php so please any tell me how to i implement this with my pictures it is most useful for me to developed my skill :)

  6. [...] Smart Image Resizer — Shifting Pixel [...]

  7. Torgils Vestad said

    Great script! I started making something similar, then i came over this and used yours instead.. thank you alot, saved me alot of work.

  8. Great script!
    Look I have a trouble with PNG files:

    Fatal error: imagepng() [function.imagepng]: gd-png: fatal libpng error: zlib error in C:\Proyectos\Webs\lt\www\image.php on line 321

    I found the solution here: http://www.jhuskisson.com/code-tidbits/from-php-4-to-php-5-php-fatal-error-imagepng

    It seems on PHP5 the quality for PNG is a value from 1 to 10. I changed the line 191 to make a try and it worked.

    Can you fix this?

    Thank you.

  9. @Taote: Thanks for pointing this out! I made some adjustments and uploaded 1.3.2. Please let me know if you come across any other issues.

  10. i use small image resize it is working perfect but when i try to use gif images it doesn’t display image how can i get this if any one help me it is very useful.

  11. who wants to combine Smart Image Resizer and TimThumb? :)

    http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/
    source:http://timthumb.googlecode.com/svn/trunk/timthumb.php

  12. now i am implement small image re-sizer in my project it is very helpful to me but how can i fix the small image re-sizer for different dimensions please its urgent if any one knows its very use full to me…

  13. [...] Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel Un script php pour redimensionner des images (tags: php script image) [...]

  14. [...] Smart Image Resizer [...]

  15. This looks good, but I can’t get it to work. If I use it like this:


    /images/image.php/the-image.jpg?width=100&height=100&image=/images/the-image.jpg

    I get an error:


    The requested URL /images/image.php/the-image.jpg was not found on this server.

    which seems quite reasonable to me – Apache is assuming image.php is a directory and it has a trailing slash.

    Is this an issue with my Apache setup? Or am I doing something wrong?

  16. Very promising script indeed, thanks! However, I noticed you use $_SERVER['DOCUMENT_ROOT'] which currently seems to break the script in my ‘userdir’ server environment…

  17. Can someone write a tutorial on how to integrate Smart Image Resizer with a content management system like wordpress or textpattern?

    It would really help out those who need need to crop and resize images dynamically but don’t understand php well.

  18. Nice idea for a script, but a quick security question—would you recommend restricting/denying any external requests for imgs via the referrer? I bet you could bring the server to its knees by automating requests for a gazillion different sizes… It could be done with another .htaccess rule. (FWIW, I haven’t looked through the code, just wondering aloud.)

  19. @Marsh: That would probably be a good idea, but if you knew what you were doing you could forge referrers in your requests so it won’t offer total security.

  20. m getting an error saying

    “Invalid src mime type: unknown”

    what does this mean????

  21. @Zinth: when the script tries to resize an image, it first performs a number of checks. One of these is the source image’s mime type to make sure it is an image (all of the mime types for images begin with “image/”). If it is not an image, it will display that error message.

    This is done to protect you against people who would try to use the script to snoop around your web server by outputting the contents of files that shouldn’t be seen by anybody (like PHP scripts and password files).

    Hopefully that helps explain things a bit. :)

  22. thanks for the script

  23. Too cool. Definitely going to use it from now on, with a mention on my blog. Cheers!

  24. [...] Lightbox, a fanastic GreaseMonkey script (for all you Firefox users out there.) It’s called Smart Image Resizer, and it’s a great piece of PHP that can resize images on the fly without modifying the [...]

  25. It resizes GIFs? It is posible?

  26. Hi guys…
    i am a new for tha PHP. but i fell thatz cool.
    can any ones teach me how to work (how to install it) it. i mean, from first step. (step by step)
    if u can itz better. i will hope you alls help. plz…..
    any ones can mail me [sjcreation@gmail.com].

    Thnx.

  27. [...] Influenced by: Smart Image Resizer [...]

  28. can somebody leave a step by step instructions…?

  29. quick directions:

    1. download script: http://shiftingpixel.com/downloads/image-1.3.3.zip
    2. open zip file, extract the included file “image.php” to “C:\image.php”
    3. upload C:\image.php to your website so the file exists at http://example.com/image.php
    4. create a folder called “imagecache” so the directory exists at http://example.com/imagecache/
    5. create a folder called “images” so the directory exists at http://example.com/images/
    6. upload an image “picture.jpg” so that it exists at http://example.com/images/picture.jpg
    7. create a php file “C:\page.php” including the source: <img alt=”my resized picture” src=”http://example.com/image.php?image=/images/picture.jpg&width=100&height=100″ />
    8. upload “page.php” so that it exists at http://example.com/page.php
    9. navigate to http://example.com/page.php and on that page you will see your image picture.jpg resized to 100×100
  30. step 6 should include:
    <img alt=”my resized picture” src=”http://example.com/image.php?image=/images/picture.jpg&width=100&height=100″ />

    (IMG tag was stripped)

  31. Thanks zach, I fixed it :)

  32. I am getting an error “image was not specifies” while adapting this image,php? in my site . can you pls help to solve this problem.

  33. @gokul: That just means that you didn’t provide the image parameter of the image you want to resize. If you can post your <img> tag here, I might be able to be more helpful. Good luck!

  34. This looks really cool, thanks.

  35. it doesnt work for me… i dont know why.. :(

    i’m using with mime GIF

    like this :

    2 folders
    /img
    and i dont why zach said to create the imagecache folder.. but it did it.
    the “image.php” is the root folder.

    home/www/image.php — your script
    home/www/img/img_semfoto.gif — Picture what i want resize.

    and still not working :( :( please help-me!

  36. @Fábio: If you access the src location you are using in your img tag directly in your browser, do you see any error messages? Are there any error messages in your error log?

  37. getting an error

  38. @Lucy: Thanks for the report. Can you elaborate anymore on the error you are getting?

  39. Cool. and its fast too :)
    THanks for making it

  40. Something isn’t working right for me when I go through all the steps. GD is running on apache, image.php is in the root, imagecache has been created and given rights, and the test image is in the root as well. I never get an image to appear, however. When I use the code from the example and it’s pointing to shiftingpixel, then I see the coffee bean example… but when using the same php code on my server, I get nothing.

    The source jpg is accessible directly, and I use GD to create thumbs already… but they are blurry… that’s why I want to use this code instead. Any and all help is appreciated. i’ll continue to troubleshoot.

  41. Parker, sorry you are having troubles. Can you post or send me a link that I can look at to help you troubleshoot? Also, can you try accessing the image script (with all of your parameters) directly in the browser (the part in the src attribute)? Are there any error messages there? Also, can you look in your PHP error logs to see if anything shows up in there?

  42. Parker Jackson said

    Solved…

    It was a server configuration conflict on my end. Schmappel had a similar issue I think… as mine was directly tied to:

    $_SERVER['DOCUMENT_ROOT']

    I replaced this code with my actual path (as found at phpInfo). Now I can start digging in and testing this out. Looks like very handy code. Thanks for posting. I will email & linkback if I put it into production. Thx ~ pj

  43. @Parker, I’m glad you got things sorted out. Thanks for coming back to post the solution!

  44. Christopher said

    erm i think it has a little problem dealing with animated gifs. it can’t load the file

  45. Any possibility to integrade with tinymce?

  46. Hey man, very useful script – and it loads fast, which is great and perfect for what I need. I was having some problems getting it to work with gifs though, and was pulling my hair out until I found a tiny error inside your ‘image/gif’ case statement (after line 256). You need to add this line to it: $quality = round(10 - ($quality / 10)); Because you’re still converting the gif to png, the ImagePng function won’t work correctly with the quality value larger than 9. Works much better now! Thanks again.

  47. [...] Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel (tags: php resize image script webdev photos) [...]

  48. [...] Очень часто возникает необходимость создания превью изображений (так называем ThumbImage). В зависимости от специфики проекта, требуется: 1) осуществлять ресайз изображений “на лету”, непосредственно при загрузке страницы; 2) ресайзить изображения при загрузке, создавая одну или несколько тумбочек по заранее заданным параметрам; 3) массовый ребилд изображений. Бывает необходим в некоторых случаях, например: каталог товаров формируется с помощью CSV-файла, в котором прописаны пути к оригинальным изображениям. Изображения загружены в специальную папку и от скрипта требуется создать уменьшенные копии оригиналов. Итак, обзор скриптов и решений. 1.Smart Image Resizer Автор: Joe Lencioni Текущая версия: v1.3.3 (Released April 28, 2008) Оф.сайт: hiftingpixel.com [...]

  49. It says the image cache directory is not writeable (chmod 775) until I give it 777 permissions.

  50. @Chris That’s because the web server is running as a user that does not belong to the group that your image cache directory belongs to. You should probably avoid setting your directory to 777 for security reasons, so you should find out what groups your web server belongs to and change the group of the cache folder to match (or change the owner of the directory to the user that the web server runs as).

    Also, ACLs may be involved, so if that doesn’t work, make sure that the ACLs are set correctly as well.

    I hope that is helpful.

  51. Ok, thank you for this useful script! I appreciate your help.

 
1 2 3 4 8