Psst! Amazon Search Suggestions just showed up.

If you want to be notified the next time I write something, sign up for email alerts or subscribe to the RSS feed. Thanks for reading.

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

Download

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

Please Digg this.

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

  • Try visiting the URL that you are using as the src attribute of your img tag directly in the browser. 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.

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/coffee-bean.jpg?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/coffee-bean.jpg?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


157 Comments

  1. So is this running the PHP script and resizing the image every time the image is loaded, or is it doing it once and keeping a copy of the image on the server?

  2. @Elliot: excellent question. If properly set up, it actually resizes the image once and keeps a copy of it on the server in a cache directory. 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.

  3. Great script! I have just started using it.


    Notice: your script sets “Last-modified” header, but doesn’t allow browsers to use their cache.

    I have added at line 177 into if($imageModified < $thumbModified) {

    these lines of code:


    // check browser cache
    $gmdate_mod = gmdate("D, d M Y H:i:s", $thumbModified) . " GMT";
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
    $if_modified_since = preg_replace(’/;.*$/’, ”, $_SERVER['HTTP_IF_MODIFIED_SINCE']);
    if ($if_modified_since >= $gmdate_mod) {
    header(”HTTP/1.1 304 Not Modified”);
    exit;
    }
    }

    with this line the script checks the request header of browser about client cache and response “NOT MODIFIED” if the image cached into browser is updated.

  4.  
  5. Cool script - I’ve actually been working on something similar. You’ve given me some ideas for improving my own script as well :)

    One thing I would suggest is checking for the cached file before setting memory limits and doing all the cropping calculations. I think that may help speed things up.

  6. @Lorenzo: aha! Silly mistake on my part. Thanks for posting this. I will make the change ASAP.

    @Ben: Thanks for the suggestions. I will try some things and include them in the next update for sure.

  7. Okay, I made some changes and uploaded it. It does seem to run more smoothly (especially with the browser cache). Thanks for the suggestions, guys!

  8. Resize images with this PHP script…

    Joe Lencioni over at Shifting Pixel, has written a post about the easy to use image resizing script. It’s a really simple script that you use by specifying the parameters in the src part of the img tag.
    The major advantage of this script is that…

  9. Nice Joe, I’m going to have to try this one out. I’m always trying to figure out the right size and uploading too may sizes to the server… anyways, nice ; )

  10. Great script. This is the marquee feature behind an enterprise product by a company called Scene7 who was bought by Adobe a few months ago.

  11. Licence?

  12. @Jaap: Good question. Creative Commons Attribution-Share Alike 3.0 United States (my attribution requirements). I will try to make that more apparent.

  13. Thanks a lot!
    This saved me a lot of time (I had actually started to write something before I found this).

    I had to add a replication for the php5 only imageconvolution() to get it to work with php4 (using oscommerce which required too many mods to get it to work on php5).

    I know it’s a lot slower, but it works.

  14. have you seen phpthumb? does pretty much the same as far as i can see…

  15. line 241 near:


    // Set up the appropriate image handling functions based on the original image’s mime type
    switch ($size['mime'])

    you may want to include:

    ‘image/pipeg’
    ‘image/jpeg’
    ‘image/pjpeg’
    ‘image/png’
    ‘image/x-png’
    ‘image/gif’

  16. nice, this is just what I’ve been looking for. thanks!

  17. How about allowing resizing of external images?

  18. Jean-Marie said

    This is great, Joe. Question: can you briefly describe how one can go about manipulating the sharpening algorithm (PHP’s imageconvolution) to adjust it to one’s taste? I find your sharpening matrix to be a bit too aggressive for my taste (i.e. too much sharpening), but I don’t entirely get how to go about adjusting the variables to apply less sharpening.

  19. Looks good. I bookmarked this for future use :)

  20. Hi Joe. I came across your little wonderful piece of code and I got so enthusiastic about it that I decided to feature it on our blog for the web community, at The Art Company — Feel free to add our link to your “Mentioned Elsewhere” list.

    Keep up the good work!

  21. Its great post! This script will make my life easier ;-)
    Thx a lot!

  22. Great script - very simple and effective. I’ve used it (after some modifications) with my Symphony site. Works grear and looks great!

  23. This looks neat. I will have to test it for real, and I guess that larger websites will need to test it thoroughly for possible performance issues, but the principle is great.

    With such a tool, you can upload a large image once, and then just ask for the right format in your templates. Great for news/content sites who use one image in 2-4 different formats (small thumbnail, medium thumbnail, page display, full picture…).

    I don’t see a lot of CMSs that offer such image manipulation possibilities. And even when they do, the content producer needs to use the tool in the right way or some things might not work. With Smart Image Resizer, you can fix this at the webdesigner level (in the website’s templates, for instance).

    Great timing, by the way. I’ve been working on a project that just needs this. Woot!

  24. doesnt appear to be working for me yet

    im running gd and php5
    on linux

    all i get is the alt tag

    dying to try it out!!!

  25. It’s a verry usefulls script, but If I am not mistaken someone can flood your filesystem by creating a lot of diferent images in the cache directory, just by making a script that change the height, width, ratio combineason

  26. @Eddy Tilmant

    .htaccess
    RewriteRule ^images/(.*).jpg$ image.php?src=$1 [L]

  27. @Zach
    It does not avoid to create thousands of files in the cache directory with a simple script

    I added it at the beginning of the script:

    
    // Check if the size is authorized
    $authorizedWidth = array ('', '120', '124','150','318', '700');
    $authorizedHeight = array ('','120', '83','150','180', '1000');
    $authorizedRatio = array('', '1:1', '1.5:1');
    
    if(!in_array($_GET['width'], $authorizedWidth)){
    	echo 'Error: This size not autorized';
    	exit();
    }
    if(!in_array($_GET['height'], $authorizedHeight)){
    	echo 'Error: This size not autorized';
    	exit();
    }
    if(!in_array($_GET['cropratio'], $authorizedRatio)){
    	echo 'Error: This size not autorized';
    	exit();
    }
    
  28. First of all, congratulations for creating a wonderful script! I encountered some difficulties at first but managed to solve them:

    1. Note that the image path must be ABSOLUTE. My development is done in a “beta” folder and as such, the image couldn’t display until I switched the path to something like “image.php/test.jpg?width=100&height=100&image=/beta/images/test.jpg”.

    2. If you still cannot see an image in the browser - try running the PHP script directly by copying & paste the image string into your browser’s address bar. This should provide some helpful error messages. Eg:

    http://www.example.com/beta/image.php/test.jpg?width=100&height=100&image=/beta/images/test.jpg

    Lastly - and here’s a suggestion to the developer for future versions - is it possible to specify the image quality? One of my thumbnails degraded very badly even in 100×100, despite its original JPG being saved at 95% quality.

  29. @Eddy Tilman

    with your script you could create a 120×1000 when you only want to allow matching dimensions.

    i would be even more specific:

    
    $image['type']=$_GET['type'];
    
    $image['thumb']['width']='100';
    $image['thumb']['height']='100';
    $image['full']['width']='800';
    $image['full']['height']='600';
    $image['tiny']['width']='16';
    $image['tiny']['height']='16';
    
    if(!is_array($image[$image['type']])){
    	exit;
    }
    
  30. Nice looking script!

    It might be nice if errors generated an image with the error text, since this script will almost always be used in an img tag and the cause of the error is not clear when you just see a broken image or the alt text.

    Also a scale option would be nice, so you can scale the image by a percentage, rather than needing to know the exact proportions of the image and do math to figure out the new width and height.

  31. Great script… I would love to see the following feature added to this script.

    Make an image (75 x 100) insert into the center of a square image of (100 x 100 white background)… this is just a fine detail issue for my usages, but I am sure alot of people would find that it would be useful.

    Great Job on this script!!!! I love it!

  32. Great Script. I have to appose the idea by Joe Harman though. You can do this with CSS / html. We don’t all have white backgrounds on our sites.

  33. 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. :)

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

  35. 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;
    	}
    }
    
  36. 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 :)

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

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

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

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

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

  42. 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…

  43. 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?

  44. 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…

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

  46. 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.)

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

  48. m getting an error saying

    “Invalid src mime type: unknown”

    what does this mean????

  49. @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. :)

  50. thanks for the script

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

  52. It resizes GIFs? It is posible?

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

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

  55. 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
  56. 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)

  57. Thanks zach, I fixed it :)

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

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

  60. This looks really cool, thanks.

  61. 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!

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

  63. getting an error

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

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

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

  67. 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?

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

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

  70. Christopher said

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

  71. Any possibility to integrade with tinymce?

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

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

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

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

  76. 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 “”;

    ?>

  77. 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 “”;

    ?>

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

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

  80. Excellent tool to use

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

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

  83. This is really great !

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

    Thanks alot !!!

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

  85. 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…

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

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

    Thanks man!

  88. 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?

  89. 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?

  90. 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)

  91. 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)

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

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

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

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

  96. 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?

  97. Great php script. thanks for sharing with us

  98. 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?

  99. 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?

  100. @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);
  101. 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?

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

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

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

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

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

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

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

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

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

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

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

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

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

  116. 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;
    	}
    }...
    
  117. 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.

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

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

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

  121. 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 :)

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

  123. 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!

  124. @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. :)

  125. Like it, very nice, Thanks

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

  127. 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”.

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

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

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

  131. 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…

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

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

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

  135. “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…

  136. (post author) Joe Lencioni said