/* --------------------------------- http://shiftingpixel.com/2008/03/03/smart-image-resizer/ 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 GD Download Download Smart Image Resizer v1.3.3 (Released April 28, 2008) Please Digg this. To Install Unzip on your web server In the same directory, create a directory called “imagecache” Make your imagecache directory is writable by the web server (usually chmod 775) 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 ----------------------------------- */ Coffee Bean Resizing and cropping a JPEG into a square Coffee Bean Resizing and cropping a JPEG into a square = $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. Ben said March 4th, 2008 at 4:59 am 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. (post author) Joe Lencioni said March 4th, 2008 at 6:52 am @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. (post author) Joe Lencioni said March 4th, 2008 at 7:00 am 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! andPHP.com said March 4th, 2008 at 10:55 am 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… Billy said March 4th, 2008 at 5:46 pm 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 ; ) David said March 9th, 2008 at 8:23 am 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. Jaap van Wingerde said March 9th, 2008 at 9:28 am Licence? (post author) Joe Lencioni said March 9th, 2008 at 9:42 am @Jaap: Good question. Creative Commons Attribution-Share Alike 3.0 United States (my attribution requirements). I will try to make that more apparent. Ekerete said March 9th, 2008 at 1:30 pm 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. barry said March 9th, 2008 at 3:20 pm have you seen phpthumb? does pretty much the same as far as i can see… zach said March 9th, 2008 at 6:13 pm 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’ lukep said March 9th, 2008 at 6:21 pm nice, this is just what I’ve been looking for. thanks! Klark said March 10th, 2008 at 12:16 pm How about allowing resizing of external images? Jean-Marie said March 10th, 2008 at 9:29 pm 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. mark said March 14th, 2008 at 2:21 am Looks good. I bookmarked this for future use :) Marc Alagem said March 14th, 2008 at 3:36 am 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! decimus said March 14th, 2008 at 3:58 am Its great post! This script will make my life easier ;-) Thx a lot! qqrq said March 14th, 2008 at 5:18 am Great script - very simple and effective. I’ve used it (after some modifications) with my Symphony site. Works grear and looks great! Florent V. said March 14th, 2008 at 7:09 am 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! Matt said March 15th, 2008 at 5:33 am 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!!! Eddy Tilmant said March 16th, 2008 at 3:16 pm 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 zach said March 16th, 2008 at 5:12 pm @Eddy Tilmant .htaccess RewriteRule ^images/(.*).jpg$ image.php?src=$1 [L] Eddy Tilmant said March 17th, 2008 at 3:05 am @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(); } Mike Tee said March 17th, 2008 at 3:06 am 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. zach said March 17th, 2008 at 11:52 am @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; } myquealer said March 18th, 2008 at 1:22 pm 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. Joe Harman said March 19th, 2008 at 11:33 am 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! Bill said March 21st, 2008 at 6:52 pm 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. Florent V. said March 25th, 2008 at 4:17 pm 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. :) (post author) Joe Lencioni said March 25th, 2008 at 4:33 pm @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. retomi said March 25th, 2008 at 7:04 pm 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 += ((0×7F000000 & $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; } } shan said March 26th, 2008 at 2:40 am 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 :) Torgils Vestad said March 29th, 2008 at 9:01 am Great script! I started making something similar, then i came over this and used yours instead.. thank you alot, saved me alot of work. Taote said April 2nd, 2008 at 6:57 am 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. (post author) Joe Lencioni said April 2nd, 2008 at 7:05 am @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. shan said April 2nd, 2008 at 8:41 am 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. zach said April 4th, 2008 at 4:46 pm 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 shan said April 4th, 2008 at 11:41 pm 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… James said April 14th, 2008 at 9:48 am 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? Schmappel said April 15th, 2008 at 10:20 am 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… Matt said April 27th, 2008 at 4:31 pm 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. Marsh said April 28th, 2008 at 11:38 am 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.) (post author) Joe Lencioni said April 28th, 2008 at 12:01 pm @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. Zinth said April 29th, 2008 at 6:12 am m getting an error saying “Invalid src mime type: unknown” what does this mean???? (post author) Joe Lencioni said April 29th, 2008 at 6:48 am @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. :) snowgirl said May 4th, 2008 at 8:36 pm thanks for the script Jeff Byrnes said May 4th, 2008 at 9:32 pm Too cool. Definitely going to use it from now on, with a mention on my blog. Cheers! Jakub Hejda said May 5th, 2008 at 2:28 pm It resizes GIFs? It is posible? Sj Creation said May 7th, 2008 at 11:43 pm 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. Mike said May 8th, 2008 at 3:42 pm can somebody leave a step by step instructions…? zach said May 11th, 2008 at 11:13 pm quick directions: download script: http://shiftingpixel.com/downloads/image-1.3.3.zip open zip file, extract the included file “image.php” to “C:\image.php” upload C:\image.php to your website so the file exists at http://example.com/image.php create a folder called “imagecache” so the directory exists at http://example.com/imagecache/ create a folder called “images” so the directory exists at http://example.com/images/ upload an image “picture.jpg” so that it exists at http://example.com/images/picture.jpg create a php file “C:\page.php” including the source: ”my upload “page.php” so that it exists at http://example.com/page.php navigate to http://example.com/page.php and on that page you will see your image picture.jpg resized to 100×100 zach said May 12th, 2008 at 8:49 pm step 6 should include: ”my (IMG tag was stripped) (post author) Joe Lencioni said May 12th, 2008 at 9:17 pm Thanks zach, I fixed it :) gokul said May 17th, 2008 at 4:41 am 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. (post author) Joe Lencioni said May 17th, 2008 at 8:35 am @gokul: That just means that you didn’t provide the image parameter of the image you want to resize. If you can post your tag here, I might be able to be more helpful. Good luck! Adaptiv Media said May 18th, 2008 at 5:36 am This looks really cool, thanks. Fábio N Sarmento said May 20th, 2008 at 6:31 pm 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! (post author) Joe Lencioni said May 20th, 2008 at 8:20 pm @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? Lucy said May 21st, 2008 at 9:33 am getting an error (post author) Joe Lencioni said May 21st, 2008 at 10:04 am @Lucy: Thanks for the report. Can you elaborate anymore on the error you are getting? fedmich said May 27th, 2008 at 3:39 am Cool. and its fast too :) THanks for making it Parker Jackson said May 27th, 2008 at 4:52 pm 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. (post author) Joe Lencioni said May 27th, 2008 at 5:58 pm 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? Parker Jackson said May 27th, 2008 at 6:21 pm 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 (post author) Joe Lencioni said May 27th, 2008 at 9:53 pm @Parker, I’m glad you got things sorted out. Thanks for coming back to post the solution! Mentioned Elsewhere 24 Times Smart Image Resizer — Shifting Pixel | The Click » Smart Image Resizer — Shifting Pixel Webcreatives Ridurre la dimensione delle immagini con smart image resizer : sastgroup.com ??? ???????? ?????? ??????????? ????? ?? ???????? ?????? | ??????? ?????? (focused.ru) Denis au fil du web » Smart Image Resizer PHP: Smart Image Resizer — Oivallisia juttuja The Abarentos Narrative » links for 2008-03-09 Martyn Davies » Blog Archive » links for 2008-03-10 links for 2008-03-10 « Mandarine ??? ??????.NET Smart Image Resizer: ???????PHP?? | ???? Carmine Web #2 » Blog Archive » Ridimensionare immagini con PHP Great Resources Elsewhere: March 07 to March 14 - CSSnewbie T’as le bonjour de Jean Rat ! » Blog Archive » Les liens sympas de Jean Rat du 14/03/08 au 15/03/08 xeRo Virtual Planet Surf Raporu, 16 Mart 2008 | Taylan Aktepe crawlspace|media » Blog Archive » Daily Ma.gnolia Links for March 16 PHP Smart Image Resizer | David Bisset: Web Designer, Coder, Wordpress Guru efrees. » Smart Image Resizer Links 3-08-08 to 3-25-08 | effectivedesign.org links for 2008-04-08 Paulan korusivut — Oivallisia juttuja Resizing images via php … hawt | [ berkleebassist ] Rayed’s Real Life » Blog Archive » Alriyadh.com image quality improvements Leave a Comment Comments You may use these tags:
Name (required) Mail (will not be published, required) Website Notify me of followup comments via e-mail -------------------------------------------------------------------------------- Must See Browse all “Must see” photos Worth a Look More Coffee Seeds Greased Lightbox v0.16 Grey nurse shark - Carcharias taurus 5 Essential Tips For Buying a DSLR Camera Sufjan Stevens playing guitar Best Chocolate Cake Ever Unjustify Tongue Yellow Ants, Acanthomyops Smart Image Resizer Holga of record player Review: Light: Science and Magic, Third Edition Latest Articles Art Show at River Rock Coffee Greased Lightbox v0.17 9rules Submissions Open May 7, 2008 Amazon Search Plugin with Search Suggestions Greased Lightbox v0.16 Review: Light: Science and Magic, Third Edition -------------------------------------------------------------------------------- Copyright © 2005-08 Joe Lencioni This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. Attribution requirements for my work. Joe Lencioni Shifting Pixel joe@shiftingpixel.com Saint Peter, Minnesota, 56082 United States of America