Psst! Amazon Search Suggestions just showed up.

If you're new here, you may want to sign up for email alerts or subscribe to the RSS feed. Thanks for visiting!

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 (a version that supports imageconvolution(), such as the bundled version).

Download

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

Tip jar


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


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

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

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

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

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

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

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

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

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

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

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

  147. thank you

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

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

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

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

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

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

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

  155. You save my life man!
    Incredible script!

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

  157. 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 :(

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

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

  160. @dan That’s a good idea, I hadn’t even considered progressive JPEGs. One thing to keep in mind though is that progressive JPEGs can’t be used in Flash.

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

  161. Hi!

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

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

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

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

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

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

  165. @Mike Yes, it is certainly possible.

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

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

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

  167. Hi Blogger,

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

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

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

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

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

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

  170. nayana adassuriya said

    great work

  171. Error if Webserver is IIS!

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

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

    Can you see this problem?

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

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

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

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

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

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

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

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

  175. Hi

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

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

    Will this script do like this?

    Thanks
    osCommerce Addon Installation

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

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

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

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

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

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

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

  181. Hi team,

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

    Please help me its bit urgent.

    am waiting for your reply

    Thanks
    RMajeed

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

    http://steven.webfizz.be/

    you can download it from there

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

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

    read write permission given to the folder imagecache..

    Error message when image src attribute pasted in browser : -

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

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

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

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

  187. Hi Steven,

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

    RMajeed

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

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

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

    Thanks.

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

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

  190. Hi!

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

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

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

    Maybe this tip could come in handy for someone?

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

  191. Hi,

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

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

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

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

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

  194. Hi,

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

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

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

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

    for your case, try using the following parameter:

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

    works for me.

  196. Hi,

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

    Cheers

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

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

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

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

  198. Thanks man,

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

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

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

    Thank you very much again! =)

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

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

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

  202. PavanPuligandla said

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

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

  203. Joe Lencioni said

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

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

  204. i am new to php and i want to use that smart image resize script but i do not know how it can be used on website?

    plz guide me,

    i will thankful to u.

    waiting for quick response.

  205. Have anybody checked this in the php version-PHP Version 5.2.9-0.dotdeb.1
    GD library- bundled (2.0.34 compatible)
    It work great in my old server but above mentioned is my current server details.
    This is not working here.No image is displayed .I can able to get the alt text only.
    No permission problem.
    What else cause this to stop working.

  206. Ravi Patidar said

    hello,
    Is there any way to use this image display by Imagemagick library? I have been used this script and it is working fine but I want to use Imagemagick library for image resizing and display them, Even I done at the level of resizing the images and also sent them the imagecache folder but unable to display those resized images.
    Please help me if you have any solution or suggestions.
    Thanks

  207. Hey, i need HELP! I’m using appServ. It’s root is “www” directory. I have a folder named “avp” in “www”. Your php file is in this directory. However, i can’t manage to show images!!! There is not enough explanation or example, please help… Thing i tried is below:

    when i make it “src=’./im….” it shows the picture. However, when i put it to web, it doesn’t work! (On the server, the file structure is the same! Everything is in “avp” folder)

  208. Great script! Exactly what I was looking for!

    This is going to be used in a photography portfolio and I’m also looking to add a small watermark to the bottom right corner of the resized image. I hope I can figure it out on my own as I’m not php-savvy, but in any case, it’s an idea for future versions :)

  209. @Jon
    If you found out how to add watermarking, please let me know! I’ve been trying to do that for a loooooong time.

  210. Me too waiting for the water marking …

  211. Joe -

    I came across your image resizer when looking for some info on TimThumb. Looks way better!

    Have you given any thought to doing a simple TimThumb emulation mode so I can drop it into my existing WordPress Theme? I am not the author of the theme and would have to hack code all over the place to swap it out, where a quick command line emulator of TimThumb would allow it to drop in to many WP blogs without much work at all.

    Couple of adds to the feature list :)

    Pass through mode, do nothing but use the passed in image, just use the same url and skip all processing (cache check, etc).
    Automatic Cache Aging some how ;)

    Anyway code and documentation look very good can’t wait for a v2 final release

  212. Hello,

    I am definitely loving using this tool– it has been a life saver! I have just one simple question, that I’m hoping someone can answer.

    After I have resized the image– how would I be able use the getimagesize() function to get the current height/width of the image? Would I have to get it from the cached folder somehow?

    Many thanks!

  213. Nevermind, it was easier than I thought it’d be. Just place the path in the getimagesize() function.


    list($width, $height) = getimagesize("http://www.yoursite.com/image.php/file-name.jpg?width=250&height=250&image=filename.jpg");

  214. First off let me say thanks for this great tool! I have a question though – in my php error log I keep intermittently finding:

    PHP Fatal error: Cannot redeclare findsharp() (previously declared in E:\sites\hydrofarm.com\image.php:369) in E:\sites\hydrofarm.com\image.php on line 379

    I’m using an unmodified version 1.4.1 image.php and looking at the code I can’t fathom why I would get that error. Any ideas?

  215. you say “intermittently”. i see E:\sites\… is the script run locally?
    are you using a cloud? it may be leftover memory

  216. Not using a cloud… we host the site locally on a dedicated (IIS) server and E:\sites\… is the physical path to the site. As far as defining “intermittently” I’m getting maybe 10 of these errors a day. The script runs thousands of times a day and while it doesn’t seem to be causing a problem, I just like keeping my error log tidy. :-)

  217. Very very nice script.

    All other scripts I found do resize the image but make it very ugly :)

    Thanks again

  218. hi, this is pretty nice.. looks well written. would be nice to have as a class or function though.. so can use it in other contexts aside from an tag.

  219. I’ve been using this script on my server for a few projects and it works fine. But today I tried using it on a client’s server, and when I try to resize a JPG, the script returns nothing (or a blank/empty image – I’m not 100% sure). Their phpinfo() reports GD version “2.0 or higher”. PNGs work fine. And the files definitely exist. Any idea what could be wrong? I’ve also noticed that when trying to access a JPG nothing is added to the imagecache folder (when you access a PNG there IS something added).

    Thanks!

  220. @steven: the first time I used this script, I run it on an IIS web server. The script gave me nothing, no thumbnail displayed.
    And then I moved it to an apache web server. And it works okay.
    I wonder if your client’s server is an IIS web server also?

  221. Joe Lencioni said

    @steven, I’m guessing that while you are using a new enough version of GD, you are not using a version that has the imageconvolution() function in it. I am using imageconvolution() to sharpen the resized JPEGs, which would explain why it still works for you on PNGs. Unfortunately this function is only available if PHP is compiled with the bundled version of the GD library.

    Some people have added a function to get around this like the one here. Be warned, however, that this function is much slower than the one available in GD and I cannot speak toward the quality of its output.

    I hope that helps.

  222. You were right – I set $doSharpen to false and it works. Thanks!

  223. I have a suspicious error that I am sick of looking at because I see no difference. Basically, I have the script in my page twice – once if there is a thumb defined for that article and one that finds the latest picture linked to that article to use as a thumb. The code for the image is the same however, its just my messy way of using ifs to change the variables within that that is different.

    When the code is kicked into gear via the latter example the source outputs:
    image.php/filename.jpg?width=/alt="Alt Text"

    The filename and alt text are correct from the database so the php making the variables is okay – therefore I dont understand that when it is bringing in the variables where thumb=1 rather than the most recent date, it works perfectly with the source reading (as it should):
    ...width=30&height=30&cropratio...

    What would cause it to ignore all the middle, put in a slash and skip to alt? The same image works in an “all images” gallery so the database data itself that I insert to do the “image=” must be okay as that particular one works elsewhere.

    Thanks if you can try and help, I am bored of looking at it now!

  224. Awesome script. Thanks for posting, re-posting and helping out the rest of us!

  225. I’m attempting to use SLIR v 2.0b2 and my server is giving me the following error:

    “.htaccess rewrite engine not allowed here”.

    Have any of you seen this error or have an idea what I might be doing wrong?

  226. Hi!

    I want to thank you so very much for this. I’ve been looking for something that will resize images without screwing up the look. I had found a “decent” one, but left the images very choppy. On top of that, it made many copies of the images. Thumbnail, crop, and the original. This one beats all that by a long shot!

    Thank you!

  227. Hi,

    Is it not possible to use images that reside on a server different from your own ? I’m trying to use the SIR script on youtube thumbnails, such as http://img.youtube.com/vi/5gUtSDQAwYw/0.jpg, but I’m getting an error saying that the image does not exist, and the path that shows up in the error has my domain in it instead of the domain of the image that I specified.

    Thanks in advance.

  228. very very cool one, thank you!!

    one very little thing i am missing: rounded corner :)
    have a look right here: http://ru2.php.net/manual/de/function.imagecopyresampled.php#80417

    and may be to have the url as a link for the script!

  229. Thanks for this excellent script! It makes image resizing sooo easy.
    An integration for TinyMCE would be great.

  230. Thank you very much for sharing! I agree integration into tinyMce would be perfect.

  231. I’m testing the SLIR beta version (SLIR v 2.0b2), and it’s working great except that the first time I request an image configuration, it returns blank, with no errors. If I reload the page, the image appears.

    Do you think this is a problem with SLIR?

  232. I’ve been trying in vain to get v1.4.1 to work and I keep getting either 404 errors (direct path to image works fine) or if I fully scope the src then I get a 403 Forbidden error. Not sure what’s up there and I was about to give up on it all.

    I decided to try out v2.0b1 and in my tests everything is working like a charm!

    Thanks a lot for this awesome script, now I just have to figure out how to work v2 so that I can add watermarks ^__^

  233. I like this script.

    One question…does it take significantly longer or is it much more intensive on the script to size, say, an 800px x 800px image down to 200×200, vs a 600×600.

    How much does it matter to the script how large the original image is in sizing it down?

  234. Joe Lencioni said

    @chris

    “.htaccess rewrite engine not allowed here”.
    Have any of you seen this error or have an idea what I might be doing wrong?

    It sounds like your web server has been set up to restrict the use of mod_rewrite in .htaccess files in that directory. This is most likely due to optimizing for speed. If you want SLIR 2.0 to work well you will probably have to mess around with your web server’s configuration files.

    @brian

    Is it not possible to use images that reside on a server different from your own ?

    The script is written to strip out the protocol and domain name portion of the image request for security reasons. With a little re-coding, you could make it so it will work with remote images, but I really don’t recommend it. You’ll most likely be opening yourself up to a whole world of trouble.

    You would be much better off writing a script that fetches the images from the remote server without requiring the URL of that remote image as a parameter (it should be all figured out internally).

    @Lukas

    one very little thing i am missing: rounded corner

    Cool, thanks for the link.

    @Simon7

    An integration for TinyMCE would be great.

    Although I probably won’t be working on anything like that any time soon, someone else here might want to take up the challenge. What, specifically, would you like it to do?

    @chris

    I’m testing the SLIR beta version (SLIR v 2.0b2), and it’s working great except that the first time I request an image configuration, it returns blank, with no errors. If I reload the page, the image appears.

    I believe that is a problem with SLIR and I most likely have fixed it in the SVN. Try checking out the latest version from the repository and let me know if it starts working as expected. Please note that the changes that are in SVN will most likely require a lot more server resources when cropping, especially if the final image is large.

    @Charles

    One question…does it take significantly longer or is it much more intensive on the script to size, say, an 800px x 800px image down to 200×200, vs a 600×600.
    How much does it matter to the script how large the original image is in sizing it down?

    It will definitely take longer and it is more intensive on the script to size an 800×800 to a 200×200 vs a 600×600 to a 200×200 image. It will, however, only perform the resize once for each image and then it is cached so the additional impact should be minimal over time.

    As far as specifically how much more intensive it is, I am not sure. The most intensive parts of the script are resizing, sharpening, and cropping. Since the final image in your test case is 200×200, sharpening and cropping should be about the same in both situations, so resizing is the greatest variable. The script uses PHP’s imagecopyresampled() function if you care to investigate further. Or, you could try a PHP profiler such as Xdebug.

  235. Cory Burke said

    Hello, I’ve been using this script, but like others – have issue with the harshness of the sharpening matrix.

    Someone in this thread attempted to create a modification which included an additional filter called “slevel” to modify the sharpening amount.

    That modification appears to no longer be available. Do you have any suggestion and or comment regarding adjusting of the level of sharpening in your script?

    Thanks a lot! Your script is fantastic but is sharpening too much for my images presently!

  236. What is new in your script compared to phpThumb? Do you have any comparison chart? I’ve not tried it yet, but I guess it may not work with corrupted images. I have very bad experience with resizing corrupted image.

    You may have a look at Problem with resizing corrupted images using PHP image functions

  237. When i try this code. i m getting this error.. any body help me on this

    Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/jooryfas/public_html/image.php on line 249

    Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/jooryfas/public_html/image.php on line 308

    Fatal error: Call to undefined function: imageconvolution() in /home/jooryfas/public_html/image.php on line 324

  238. This is going to save me a ton of time on a project I am working on right now. Thank you!

  239. Joe Lencioni said

    @Cory Burke

    Do you have any suggestion and or comment regarding adjusting of the level of sharpening in your script?

    Although I am not sure of what you would need to specifically do to adjust the level of sharpening, you should probably look at lines 310–325 and 369–379 in v1.4.1

    @adnan

    What is new in your script compared to phpThumb? Do you have any comparison chart?

    I’m not sure, I’ve never really looked at phpThumb.

    I guess it may not work with corrupted images.

    I am betting you are correct.

    You may have a look at Problem with resizing corrupted images using PHP image functions

    After reading that article and poking around, I believe phpThumb can be configured to use ImageMagick, which may be a little more flexible and robust than GD.

    @Rifath

    Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/jooryfas/public_html/image.php on line 249

    Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/jooryfas/public_html/image.php on line 308

    It is hard to say what is going on without more information. However, it looks like you may be trying to resize an unsupported type of image. Perhaps it is corrupted or saved in a weird format.

    Fatal error: Call to undefined function: imageconvolution() in /home/jooryfas/public_html/image.php on line 324

    This means that you don’t have the imageconvolution() function in your copy of PHP. According to the PHP documentation, imageconvolution() “is only available if PHP is compiled with the bundled version of the GD library.”

  240. Here an improoved version
    http://luciorota.altervista.org/xoops/modules/wfdownloads/singlefile.php?cid=2&lid=13

    now is possible to apply filters to images (experimental)

  241. The script seems to be working great except for one thing … when I try to resize to a 3000x 2000 size. I want to provide an option to resize the file into 4 different sizes:
    3000 x 2000
    800 x 600
    480 x 340
    540 x 360

    The code is the same for each (except for the width/height and cropration) yet the 3000 x 2000 doesn’t output (though it appears to think awhile.

    Any ideas?

    Here’s the specific code line:
    “;

  242. @chris

    I’m testing the SLIR beta version (SLIR v 2.0b2), and it’s working great except that the first time I request an image configuration, it returns blank, with no errors. If I reload the page, the image appears.

    I believe that is a problem with SLIR and I most likely have fixed it in the SVN. Try checking out the latest version from the repository and let me know if it starts working as expected. Please note that the changes that are in SVN will most likely require a lot more server resources when cropping, especially if the final image is large.

    @Joe

    It’s working great now with the new version, thanks!

  243. Scott Alexander said

    Thank you for this script. It was very useful for a project I’m working on, and it is going to be a lifesaver in a project I have coming down the pipeline. Is there a mailing list so I can be updated if you update the script?

  244. hi joe,
    we are using a mod_thumbsup mod based on your image resizer 1.4.1
    on our joomla based site. it was working great until we transferrred servers to godaddy. now, none of the thumb images are showing, just the text, ie dont.jpeg. i read through & the dev tried the fixes above but to no avail.
    any suggestions?
    thanks!

  245. Sometimes, the output image is one pixel larger than the specified.

    This is caused by ceil() function. If you change all ceil() functions to floor() it will be solved.

    shr3kull

  246. Thanks for the script:)

    I was using phpthumb but found it slow and unreliable in caching images. Your script seems a lot more robust.

    I’ll definately check out V2 when it’s stable.

    Thanks again.

  247. Timon Bergen said

    This script looks great, and I started enthusiastically to include above code into my website. Unfortunately it is not working!

    When I enter following URL, it returns a error.

    http://www.websitename.nl/image.php/1.jpg?image=/images/1.jpg&width=100&height=100


    Parse error: syntax error, unexpected T_IF in /home/abc/domains/websitename.nl/public_html/image.php on line 17

    I really want to use this code, because I intend to use 3 different thumbnail sizes.

    Can anyone please help me?

  248. Can somone please let me know why this wont work for me?

    test url is http://caseykluver.com/reclaimed/

    Everything is the same as the examples except the image.

  249. Oh yeah, the error is PHP Warning: Cannot modify header information – headers already sent by (output started at /home/mkadesi/public_html/caseykluver.com/reclaimed/image.php:2)

  250. Hello there,

    This is indeed a wanderful script, very close to what I was looking for. I’m currently working on a site that has a gallery of photos under each chapter, and would really like to use your script for generating thumbs. Unfortuantely, since there are sometimes up to a hundred photos in each gallery I find it very tiresome to change image size for each image (it kind of defeats the purpose of having a script for it). Is there a simple way you could define size of thumbnails as a constant for each gallery, so that you only have to change size once for each page and all the images would resize to the same width/height? Might be a silly question, but PHP is still new to me..

    thanks a lot and keep up the good work.

  251. Thanks for a great script.

    The only thing is that the sharpening is to high.
    Thumbnails looks way to sharp, so I turned that feauter off.

    Perhaps you can adjust the sharpening setting in feature versions?

  252. Hi Joe,

    Thanks a lot for this script. It works beautifully on Apache on Windows but for some reason when I transfer my application to Ubuntu Linux it does not.
    I’ve tried following all of the troubleshooting steps suggested above without success and now have to ask you. I get the following error when I try to browse to the url directly:

    Error: no image was specified: 1

    I added the the ’1′ to my script to differentiate between the two places where this error is returned. In my case this occurs on the first instance, right at the beginning of the script, indicating that the ‘image’ parameter has not been set in the GET request. Here is my url:

    http://www.honeydoilookfat.com/resize_image.php/image-name.jpg?width=358&height=370&image=/upload/butt_5.jpg

    Clearly it has been set. My phpinfo information can be accessed here:

    http://www.honeydoilookfat.com/phpinfo.php

  253. Hello,

    The script is working great, but with some (large) images I get the following error:

    Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 12000 bytes)

    How can I fix this? The image I used is 1.6 MB, is it to large?

  254. Is there a limit to the filesize?

  255. Looks like a really good script. Thank you for publishing this.

    I just read all the comments, and it seems like quite a few people would like to add a watermark. Did anybody figure out how to do this? Thanks.

  256. It’s possible to customize the v1 script for watermarks. I paid a student $60 to do it and he said it was really simple – but he didn’t do exactly the way I wanted it, that would’ve cost additional and I couldn’t afford it for my non-profit site.

    His script merged the original image and the watermark _before_ the resizing, so the watermark size depended on the original image resolution. Higher res picture -> smaller watermark. Ideally, watermark should be added after resizing so it’s consistent.

    For my usage, it doesn’t matter, because all my original images are the same resolution at the time being. I’m just saying it’s possible and not that difficult.

    Please don’t ask me to share the modified script, I will also not sell it because it is still Joe’s property. I suggest that Joe finishes v2 and charges for the advanced features. I’d gladly pay $20+ for a good script.

  257. I have been trying for days to get TimThumb to work, and I gave up. I found your script. 15 minutes later, it is working on my site (http://simplecomplexity.net/visualization-gallery/). Thank you sooooooo much!!!!

  258. Hello everyone.

    I read a lot of comments along the lines of “How do I add a watermark automatically to the image?”

    I’m here to provide a solution for you! (Because I’m awesome). This solution will apply the watermark AFTER the image is resized. The cached image will contain the watermark.

    I ask only one thing: if you use my solution, please send me a quick message with your website link to email: ( hello — at — scottalex.me )

    Solution:
    First, goto line 308:
    ImageCopyResampled($dst, $src, 0, 0, $offsetX, $offsetY, $tnWidth, $tnHeight, $width, $height);

    Add this code under that line:

    // ** WATERMARK IMAGE MODIFICATION ** //
    // By: Scott Alexander
    // http:///www.scottalex.me

    // ** CONFIGURATION **
    $watermarkPNGFile = “WATERMARK_PNG.png”; // Must be PNG
    $watermarkMargin = 5; // The distance from the edge of the bottom right corner
    $watermarkOpacity = 75; // The opacity of the watermark
    // ** END CONFIGURATION ** //

    // Load watermark image into memory
    $watermark = imagecreatefrompng($watermarkPNGFile);

    // Get watermark image dimensions
    $watermarkWidth = imagesx($watermark);
    $watermarkHeight = imagesy($watermark);

    // Get image dimensions
    $imageWidth = imagesx($dst);
    $imageHeight = imagesy($dst);

    // Calcuate where we need to place the watermark
    $placeWatermarkX = $imageWidth – $watermarkWidth – $watermarkMargin;
    $placeWatermarkY = $imageHeight – $watermarkHeight – $watermarkMargin;

    // Merge image and watermark
    imagecopymerge($dst, $watermark, $placeWatermarkX, $placeWatermarkY, 0, 0, $watermarkWidth, $watermarkHeight, $watermarkOpacity);

    // ** END WATERMARK IMAGE MODIFICATION ** //

  259. Hello all,

    Scott of http://www.scottalex.me here again~

    If you wish to disable direct access to your images, simply put this in your image folder(s)

    Filename: .htaccess

    Contents:

    RewriteEngine on
    RewriteRule ^.*$ http://www.mywebsite.com/ [R]

  260. Why dose one HAVE to use a absolut path to the file? This dosn’t work at all with my project. Is there a way around that? Thy for your help in advance!

    Clay

  261. This script would be absolutely amazing if it used relative file paths instead of absolute file paths.

  262. So if/until this script is updated to use relative file locations, just append $_SERVER['REQUEST_URI'] to the beginning of your images.

    For example:
    $curdir = $_SERVER['REQUEST_URI'];
    echo ”;

    Obviously this only works on php enabled pages.

  263. How to add cache header to this images?
    I have tired in few places ,but i couldn’t .
    Please advice me.

  264. This is amazing thank you. I am concerned about access and people knowing I use this or how to access it directly, I like the idea above about authorized sizes and I will probably add that at some point.

    To hide the script itself I am using mode rewrite to set fake image locations to specific sizes with a mod_rewrite rule. Also along with that I am sending a unique security key string that I have added a check for at the top of the script.

    #example path /images/story/100/thumb/10.jpg
    RewriteRule images/story/(.*)/thumb/(.*)$ image.php/$2?width=130&height=130&cropratio=1:1&image=/images/story/$1/$2&cachekey=complicatedkeystring

    // custom access handling
    $cachekey = ‘complicatedkeystring’;
    if ($_GET['cachekey'] != $cachekey)
    {
    header(‘HTTP/1.1 400 Bad Request’);
    echo ‘Error: unauthorized image access’;
    exit();
    }

  265. Kerry Usry, it’s a very good idea indeed to add the security measures.
    Without the security, some bad guys can drain out our bandwidth resources.
    And I found out also that big size thumbnails (say 400 x 400 px) sometimes have bigger filesize than the original picture. An original picture of 200KB filesize might have a 300KB thumbnail.
    Now if some bad guys access our script directly like Kerry Usry said, our imagecache folder will get amazingly huge thanks to tons of big image cache files generated by them. It can eventually reach the disk space quota of our website hosting.

  266. @Joe Lencioni

    First off, thank you so much for this script! Before the launch of our site we were using your original SIR script locally without incident, but once we pushed live we could no longer get the script to work. However, we were able to get things working on the web server with the new SLIR (slir-2.0b2.zip) you posted.

    While the resizer seems to work great, at times things can be really slow, even after cached images already exist. Here you can see our latest build of InternetGentleman.com. Things can be really snappy for a time, but then randomly the page will take a while to load, especially on our archives page.

    We’re resizing images on our own to keep the original image size down, but we’re relying on the script to generate the various sizes for us. We obviously have a lot of variables at play here, but we’ve eliminated just about all of them and the issue still exists. Do you know of a way we could improve the speed of the resizing/scaling in the script? If not, can you recommend a way to troubleshoot this problem so we can determine if it can in fact be fixed?

    Any help/advice would be much appreciated! Feel free to email me directly!

  267. Joe Lencioni said

    @Adam

    While the resizer seems to work great, at times things can be really slow, even after cached images already exist.

    I believe there may be some bugs in the latest beta release I have up on Google Code. Try grabbing the latest from SVN and let me know if you notice any issues. The latest SVN will use more system resources to crop photos the first time around, but caching should work better I think. I need to get a new beta release out, maybe I’ll be able to find some time in the next couple of months.

  268. @Joe Lencioni

    Thanks! I’ll pull down the working copy, test it, and let you know if we notice an improvement.

  269. Problem faced everytime used image resizer, every times it shows the error:

    Fatal error: Call to undefined function imagecreatetruecolor() in E:\wamp\www\nasir\Real Estate Zameen Clone\Online_\image.php on line 249

    I unable to find this function defined anywhere in the script, Is this a ready function means defined in php.ini ???

    Please solve my problem!!

  270. How do I make the rewrite thing you have ?

    I saw earlier in the comments one made it like /path/200/300/1:2/image.jpg

    but the down side is that I’d have to use them all.
    On this website its like

    /path/w200-h200/image.jpg
    or just /path/w200/image.jpg works aswell.

    Mind sharing that htaccess for us :)

    thanks in advance,
    Tem

  271. Michael Drogan said

    Hey i am completely new to all of this, and im am wondering where to start. Do i put this code somewhere in another page that has images? or do i put inmages in the same folder? or do i put images on this page? i have no idea where i am at.

  272. I cant seem to run the script with relative paths, however when using absolute paths all is fine.

    BTW Thanks for the awesome script

  273. Many thanks for this great and really useful script.

    It would be great if it would be mentioned in the documentation somewhere that it needs the FULL path to work and does not seem to work from a subdirectory path.

    Thanks a lot
    tobias

  274. Thanks for the great script!
    I’m testing the latest version from the repository. It worked great the past weeks in my test environment. But now it’s giving me an error when a resolution of the image is called for the first time by the script. The script does cache the image to it’s appropriate size, so the 2nd+ time the image is called no error occurs. The error is (displayed in an image):

    2048 Declaration of PelEntryUserComment::SetValue() should be compatible with that of PelEntryUndefined::SetValue()

    File: [path]/pel-0.9.1/PelEntryUndefined.php Line 285

    Quite weird since it didn’t give any errors before. I tried numerous images and also images which worked before.

    Any ideas what might cause this problem? Thanks

  275. Hi,

    what rewrite script are you using on shiftingpixel.com to make the imgurl’s look like this:
    shiftingpixel.com/slir/w200-h200/wp-content/uploads/2008/03/coffee-bean.jpg

    I tried the one above, but that one required all paramters to be filled. The one SP.com is using also works with only “h300″, or only “w150″.

    Greetings and thanks in advance,
    TeMc

  276. Hi,

    Thanks for this awesome script! I’ve used it in a couple of projects without any problems at all. It’s brilliant!

    But on this one project I keep getting an error:
    Fatal error: Call to undefined function imageconvolution() in /var/www/web0/html/slir/slir.class.php on line 494

    The webserver is running PHP 5.2.6-1+lenny3 with GD enabled.
    In phpinfo() it says “GD Version: 2.0 or higher”.
    It doesn’t say “bundled” or anything like that, though.
    Could this be the problem?

  277. Hi,

    I have two questions:

    1. Why the images when are cropped and selected them, presents a “margin” of 5px in bottom of the image?

    2. One image was cropped wrong. All images cropped with 180X180px and it in 181X180, what´s happening?

    Thanks

  278. A comment on your example code:

    is the “…/coffee-bean.jpg?width=…” part necessary? I’ve dropped it from my URLs and the script still works fine.

    Also, I had to replace “&” with “&” to make it work.

    Thanks for the useful script.

  279. WilderBeastFiascoFantasticFunTimeSpiritJourneyAllAroundGoodTimeHats said

    Will it resize to proper proportions if you only specify width or height?

  280. @ WilderBeastFiascoFantasticFunTimeSpiritJourneyAllAroundGoodTimeHats:

    Yes…

  281. i’m using the version that we can download on this page.
    I wonder if there is any possibility to make this work on css url to, like:

    background:#2770B9 url(../images/image.png) repeat scroll 0 0;

    and if it is, how to do it.

  282. @Tom,

    I was having the same error. BTW @Joe not only a very nice script but very handy having the errors returned as an image. This allowed me to trace the error to the lib which was trying to copy the EXIF data to the smaller image. I don’t know why the error occurs but I don’t need the EXIF data copied so I set this to FALSE in the slir-config and the error went away. You may want to change your img alt tag to say image loading cause it takes a sec for it to come across.

    Once again very nice Joe, thanks!

  283. Daniel Rauch said

    A quick fix for people getting reaching the memory limit with big images:

    find the following line

    ImageDestroy($src);

    and move it up so it comes directly after the following line

    ImageCopyResampled($dst, $src, 0, 0, $offsetX, $offsetY, $tnWidth, $tnHeight, $width, $height);</code

    that frees some unneeded memory a little earlier than in the original php script and we get it to process bigger images.

  284. Hi again,

    My questions is in air yet. Someone hs the same problem and how resolved it?

    1. Why the images when are cropped, they have a “margin” or “padding” of 5px in bottom of the image?
    When I have a border of image this border become bigger than I put in CSS border.

    2. One image was cropped wrong. All images cropped with 180X180px and it in 181X180, what´s happening?
    This isn´t important for now, but I would like to solve this to.

    Thanks in regard.

  285. After not being able to get TimThumb to work for my project (and no idea why), I was able to get this plugin working beautifully. Thanks much!

  286. Just for all who want a little less sharpening:

    just play a little bit around with the integer value of $a in the function findSharp(). It´s default of 52 is relatively sharp, whereby 55 is far less sharp and 48 is extra super sharp.

  287. Been using SIR for a while now, it’s great.

    Any chance of allowing the source image file to be pulled from another server, for example flickr?

  288. I too am getting this error with larger images:

    Fatal error: Allowed memory size of 104857600 bytes exhausted (tried to allocate 26536 bytes)

    This happens for images greater than about 5MB.

    I’ve confirmed using phpinfo that my memory_limit is set to 64M. So this script should be able to handle a 7MB file, right?

    BTW, the error message is credited to this line in your code:

    $src = $creationFunction($docRoot . $image);

    Otherwise though this script is awesome.

  289. @Dan
    Did you try the fix i posted a few comments above?
    (it will allow using a bit larger images bevor reaching the memory limit)

    The filesize doesnt really matter. Its the number of pixels in the image and at some point the memory needed to store and manipulate (resize and sharpen image) them is larger than the memory limit (however high it may be).

  290. @Daniel: I just made the change you recommended, to avoid out of memory errors. But previously I increased the memory allocation in the script from 100M to 200M and that worked. Hadn’t realized that your script was re-setting the memory allocation setting for php.

  291. What a fantastic script and kudos to you Joe for giving back to the online community like this.

    I’m working on a new project at the moment and wondered…going forward, will you support this for the next couple of years or so or is it a case of, once it is working, it won’t need any updates. I’m just concerned about possible new releases of PHP etc not being compatible and all my site images breaking in one day?

    Thanks

  292. @Tim: good question. I have been focusing most of my energy on the 2.0 version, so when that is done hopefully it will fit your needs going forward.

  293. Great – thanks Joe!

  294. Animated GIFs are converted to static gifs by the resizing process.

    Any way to handle this better?

    Would be nice to resize it, like all other image types.

  295. Hi, this seems like a fantastic script, but I’m looking to make some small modifications to it for use in my own project. I’m using CakePHP to create a site. One consequence of this is the fact that images displayed via the URL of:

    http://something.com/img/image.jpg

    are actually hosted at:

    /root/app/webroot/img/image.jpg

    This, I can see, could cause some confusion when it comes to referencing images. As a result of this, I was wondering if it were possible for the path to the image to be relative? I.e. if I store image.php in:

    /root/app/webroot/

    so I can send it a relative image reference, i.e.:

    image.php?image=/img/something.jpg

    rather than:

    image.php?image=/root/app/webroot/img/image.jpg

    to make life a little easier.

    How hard would this be to do?

    Thank you

  296. Great script…. we had been searching for something like this for a long time and this one really fit the bill. One request: would it be possible to have parameter to restrict the image by width OR height and set the crop x-y? For example, it would be great to take a 300 x 222 image and constrict it to 300 x 200 center cropped, shaving 11px off the top and bottom.

    Thanks much. We just implemented this and it works great.

  297. Hi good script , but found something wrong in this script may be you can fix it earlier. If directory name contains word like ‘+’ sign in url then it would not find the image as url broken.

  298. Ok i did it by using rawurlencode function with path. I thought to save your time by telling this :)

  299. Why you did’t write this in oop manner so its actually reusable ??!?!?!

  300. ok next time i will write in OOP manner if found something wrong, i write short to save your time and mine .thx

  301. Joe Lencioni said

    @Dan: It would be nice if it handled animated GIFs, but that isn’t something that I have had time to implement yet. I believe that the process would involve splitting the GIF up into its frames, resizing each frame, and the re-splicing it back together.

    @Daniel: That is actually how it is designed to work. You should be able to use a relative image request (image.php?image=/img/something.jpg).

    @Trevor: You can do this. Just set the crop-ratio to 3:2.

    @Rizwan: Yes, you are correct. For URL parameters that contain reserved characters like plus signs to work, you will need to escape them somehow. As you mentioned, PHP has a function for this called rawurlencode().

    @WTF: I have been working on an OOP version that you might want to check out. If you do, be sure to grab the latest from the SVN (currently at r77) instead of the 2.0b2 download. Although, most of the methods are restricted so I am not sure how “reusable” it will be out of the box. With a little tweakage I don’t think it should be too bad. What specifically did you have in mind?

  302. Hi , can anyone to say what is performance of the script comparing with direct image access?

  303. Hello!
    Great script, thanks for sharing.
    I’ve integrated my script in my CMS, but… there is a serious problem…
    The leverage browsing cache is not work using this script.
    So, the images is served correctly, and not scaled in HTML… this is very good, but the browser cache is not working.
    This is more evident using Internet Explorer 8. If you refresh the page, you see that the images are loaded/downloaded again!
    The rule:

    Header set Cache-Control “max-age=29030400, public”

    is not working, all the images are dowloaded ex-novo all the times!
    I have used a rewriterule to have clean urls, the cached images as the originals.
    However the images are loaded all the times and are not cached by the browser.
    This makes the script useless for performaces purpose and to remedy to the problem of HTML scaling… but with the HTML scaling all the images are cached by the browser.
    Can you fix this?
    Regards.

  304. Oh another things…
    Do not use Etags, it’s slow down the website performances.
    I tried some experiment with your script into a real remote server.
    It seems that there is a mistake with your header() functions, because invalidate all the directive with apache (about caching).
    Plz, remove etags, first of all.
    Take a look here: http://developer.yahoo.com/performance/rules.html
    Anyway your script is good.
    Back to more update (I hope!)
    Regards.

  305. Hi Master,
    You can explain me ¿How to use this script in wordpress dinamically? I can’t get that this script works..You can help me please?
    Thanks in advance.

  306. Read the comment of zach.
    You must replace img src=yourpic with img src=image.php etc.
    Anyway there is a problem with the cache, if you are not using the cache rules (Apache) you’re ok.
    Using this script you get “200 ok” instead of “304 not modifyed”, so the thumbs are reloaded all the time.
    Tested on hostgator, using Pagespeed and Live HTTP headers (firefox plugin).
    So, I’ve removed the script from my CMS :-(
    Awaiting the response/suggestion of Joe.
    Regards.

  307. @Ottiv: You should check out SLIR 2.0 and let me know what you think. I just uploaded b3.

  308. Comments are now closed on this post. I have set up a Google Group for discussion and community support.

Mentioned Elsewhere 62 Times

  1. Smart Image Resizer — Shifting Pixel | The Click
  2. » Smart Image Resizer — Shifting Pixel Webcreatives
  3. Ridurre la dimensione delle immagini con smart image resizer : sastgroup.com
  4. Как изменять размер изображения прямо из адресной строки | Простые фокусы (focused.ru)
  5. Denis au fil du web » Smart Image Resizer
  6. PHP: Smart Image Resizer — Oivallisia juttuja
  7. The Abarentos Narrative » links for 2008-03-09
  8. Martyn Davies » Blog Archive » links for 2008-03-10
  9. links for 2008-03-10 « Mandarine
  10. Тут Хумора.NET
  11. Smart Image Resizer: 智能图像缩放的PHP脚本 | 帕兰映像
  12. Carmine Web #2 » Blog Archive » Ridimensionare immagini con PHP
  13. Great Resources Elsewhere: March 07 to March 14 - CSSnewbie
  14. T’as le bonjour de Jean Rat ! » Blog Archive » Les liens sympas de Jean Rat du 14/03/08 au 15/03/08
  15. xeRo Virtual Planet
  16. Surf Raporu, 16 Mart 2008 | Taylan Aktepe
  17. crawlspace|media » Blog Archive » Daily Ma.gnolia Links for March 16
  18. PHP Smart Image Resizer | David Bisset: Web Designer, Coder, Wordpress Guru
  19. efrees. » Smart Image Resizer
  20. Links 3-08-08 to 3-25-08 | effectivedesign.org
  21. links for 2008-04-08
  22. Paulan korusivut — Oivallisia juttuja
  23. Resizing images via php … hawt | [ berkleebassist ]
  24. Rayed’s Real Life » Blog Archive » Alriyadh.com image quality improvements
  25. links for 2008-06-11 « RabiFoot at wordpress.com
  26. Создание ThumbImage (эскизов) средствами PHP | Блогово Зайсла
  27. 100 Scripts and Script Resources | OpenJason
  28. Three Years — Shifting Pixel
  29. Script para redimensionar imagenes con PHP y GD | Seraphinux
  30. Geradores de thumbs - dump
  31. Smart Image Resizerphp and javascript
  32. Tired Robot » Blog Archive » Smart Image Resizer (PHP): a simple way to create thumbnails and more on the fly — Shifting Pixel
  33. Smart Image Resizer PHP: Uma forma muito simples de redimensionar imagens « Michael Granados
  34. PHP класс Image Resizer | Блог веб-разработчика
  35. PHP Foto verkleinen croppen script |
  36. Three Years | cameratraveller.com
  37. Smart Image Resizer | Web Services and Tools
  38. Humanboy | Blog » Blog Archive » Projects I’m working on 09/24/08
  39. Smart Image Resizer | HTML PHP CSS Web 2.0
  40. PHP ile Resim Boyutlandırma Scripti | EBüyükkaya - Not Defterim
  41. Smart Image Resizer Script (PHP) | CRTBS Talk
  42. Личный блог InDel-а » Blog Archive
  43. Smart Image Resizer | SulVision
  44. links for 2008-12-23 | Yostivanich.com
  45. 20 Useful PHP Components & Tutorials for Everyday Project « Hdeya team blog
  46. Angels Picks » Blog Archive » 20 Useful PHP Components & Tutorials for Everyday Project
  47. 20 Useful PHP Components & Tutorials for Everyday Project | Programming Blog
  48. 20 Useful PHP Components & Tutorials for Everyday Project | Noupe
  49. 21 полезный компонент PHP | Блог Web-мастера | Блог Web-мастера
  50. Smart Image Resizer (PHP): a simple way to create thumbnails and more … « DevEzine
  51. Smart Image Resizer PHP: Uma forma muito simples de redimensionar imagens | DGmike
  52. PHP ile Resim Boyutlandırma Scripti | EBüyükkaya | Not Defterim
  53. The Photo Guide, my final year project | Codefor
  54. To procrastinate is to procreate ideas in your brain | qrisper
  55. Awesome image resizing script - WuLongTi’s Words of Wit
  56. Lack of updates courtesy of PHP security issues
  57. Use a thumbnail (or feature image) for your post automatically | WP Kode
  58. Image Resizing Script « Designed by Sarah
  59. Spectre (Portfolio) | Quest For News, A TUTORIAL Base
  60. php image thumbnail | Doyyy.com
  61. Image Upload and resize with php | TechiePark
  62. Smart Image Resizing in CakePHP - Marshall Thompson