Joe Designs

PHP image on the fly resizing with caching, and croping.

September 2nd 2008

Edit: Feb 5th 2012 1:34 PM

Thanks to palepurple some needed updates have happened to this script.


  • 2012/01/30 - David Goodwin - call escapeshellarg on parameters going into the shell

  • @param string $imagePath - either a local absolute/relative path, or a remote URL (e.g. ). See SECURITY note above.

  • @param array $opts (w(pixels), h(pixels), crop(boolean), scale(boolean), thumbnail(boolean), maxOnly(boolean), canvas-color(#abcabc), output-filename(string), cache_http_minutes(int))

  • @return new URL for resized image.

Edit: July 1st 2009 1:46 AM

There is a new version of php image resize which now supports remote images, you can download it now or visit the github page here:

Visit PHP Image Resize (GitHub)

There is also a new example page included in the repository.


Just thought I would share a recent function that we have built to resize images on the fly, so if you have an image that is 800x800, and you want to make a thumbnail to 200x200 just use the function like this:

<img src="<?php echo resize("PATH_TO_IMAGE",array("w"=>200,"h"=>200)); ?>" border="0" />

Be sure to check out the example page.

Configuring is pretty simple, just make sure the cache directory that you choose is writable by the server, and you should be up and running.

The script will compare the generated images timestamp to the original image's timestamp, so if the original image is changed all cached images will be re-built.

I hope you enjoy, and let us know if you have any questions, thanks!


Dan says...
First off, great script! My jaw dropped when I tried it and it actually worked without me having to mess with a ton of settings.

Question. If an image has a transparent background like a .png, it receives a white one when it's resized. Is there any way to change the background color so that it matches the site better?
Wes says...
Hey Dan, Thanks for the comment! Yup it will work with transparent backgrounds. I just added a couple of things to the function to accommodate this.. Take a look at the example page towards the bottom, and download the new version. Let me know how it works for you.
Jane M. says...
Yes! It worked right out of the box.. I love it! Thank You So Much!!!!!
Dan Grey says...
Hi! is this php5 only? I can't get it to work with php4.

Wes says...
I believe it should work for php4 too, you just need to make sure ImageMagick is installed and working for php4.
Vahur says...
My original code is:
printf ("<a href='files/%s' target='_blank'><img src='files/%s' width='200' border='0'></a>", $myrow['pilt'], $myrow['pilt']);

I dont understand why can i made this code work width image resizer - i haw only error
thegirlinthecafe says...
I just want to say thank you for the script. It works right out of the box, brilliant! :)
Paul says...
I'm having a few difficulties with the script.

First of all I get the following error messages:

Notice: Undefined index: h in C:\Users\paulatop\wamp\www\temp\resize.php on line 22

Notice: Undefined variable: h in C:\Users\paulatop\wamp\www\temp\resize.php on line 32

Notice: Undefined variable: h in C:\Users\paulatop\wamp\www\temp\resize.php on line 58

Notice: Undefined index: maxOnly in C:\Users\paulatop\wamp\www\temp\resize.php on line 83

I am able to remove the notices by using the suggestion from here:

I have configured the cache folder correctly, I echoed the $cacheFolder to be sure.

The thumbnails simply don't generate.

I've been testing this with wamp on vista and xp. Both have the same outcome.

Do I need a plugin such as ImageMagick to make this work?
Wes says...
Hi Paul.

Yes ImageMagick is required for this script. In some cases the 'convert' command path to ImageMagick may vary on different servers.
Paul says...
Thanks Wes,

I installed ImageMagick and got the demo working. I've been playing around with it a bit and found a couple of things:

- Images with spaces in their names don't work. Maybe a str_replace can be used somewhere to fix this.

- on line 25 there is the following line of code:
$imgPath = str_replace('.'.$ext,'',$imagePath);
I can't find the variable $imgPath anywhere else, so not sure if it is needed?

- to find the maximum allowable height or width change the line:
if($width > $height){

$widthPercentage = $width / $w;
$heightPercentage = $height / $h;
if($widthPercentage > $heightPercentage){

Hope these are constructive.
Paul says...
Figured out how to handle files with spaces. You need to put quotes in the command line specifically arounf the $imagePath. For example change:

exec("convert ".$imagePath." -resize ".$resize." -quality ".$quality." ".$newPath);


exec("convert \"$imagePath\" -resize ".$resize." -quality ".$quality." ".$newPath);

xuan says...
It is a very nice srcipt......THANKS
speng says...
Hi, it is a nice script.
It run perfectly in my localhost testing but it didnt work online.

exec("convert ".$imagePath." -resize ".$resize." -quality ".$quality." ".$newPath);

Is it because this line of command only work in window but not linux??
aaron says...
just like every other image resizing script I find, can't get it to work, not sure why... but it seems that they aren't as simple as unzip, copy, paste.... cause it's not working
Wes says...
Hi Aaron,

The script is designed to use ImageMagick and PHP, if you have those two installed and working properly, check your cache folder's permissions. Let me know if your getting any kind of errors.


You may want to check your online machine's path to convert. Try "whereis convert" and see if you can find convert in a different location.
Beauford says...
Works good, but what would be great is a feature that would be able to resize an image from a remote site, like photobucket. I allow users to link pics, but I want to be able to control the size. Any chance of this?
Wes says...
Hi Beauford,

Yup, I've actually got a new version of the script that supports external image requests then cache's the resized image locally. I'll be posting a version on github soon, i'll link to it here when its ready! Thanks for the interest in the script.
Anshuman says...
The Demo throws up a 403 Forbidden...!
Wes says...
Ahh, there was a bad link to the demo.. just fixed it. thanks for the tip
swapna says...
Thanx for ur wonderfull script but when i'm running this script images are not displaying
please tell me what is the mistake.
Wes says...
Hi swapna..

It could be a number of reasons, what kind of server environment are you running? Do you have ImageMagick running? Have you checked your cache folder's permissions? Make sure your site can write to your cache folder and be sure you have ImageMagick configured correctly.

simha says...
External Image resize is not working

:( what may be the problem??
mores says...
Finally an image resize script that works.

Now I only have one issue: can we have ZoomCrop?
I'd like to get rid of the black bars on the side when cropping, I want the image to fill out the entire dimensions I specify.
Like timthumb ;)

Oh, and another issue: I'm trying to get this done in WordPress. Since WP uses absolute links, this script interprets these as external links ... any idea how to avoid this duplication of images that already are on the server?
mores says...
Okay, let me answer my second question myself.

Look for
<b># check for remote image..</b>
Under this line you'll find a bit of code that checks the image url if it contains "http".
Ich changed this to
<b> if((ereg('http://',$imagePath) == true) && (ereg('',$imagePath) == false) ):
For my domain, obviously.

After this check, add this to get rid of the absolute url and make it a relative url:
<b> if (ereg('',$imagePath) == true):
$imagePath = ereg_replace('', '', $imagePath);

Now, how do I get zoomcrop :)
Wes says...
simha: looks like its working? or at least I see a small resized pic :) Sorry I didn't get back to you earlier.

mores: Looks like you got this figured out, you could have just linked to the in the resizer var.

When it looks for an image it copies it over and caches it so it doesn't necessarily need to grab the external image everytime :) Save some bandwidth here and there
Rut says...
Hi! Thanks for the script! :) But can you explay, please, how use it with Wordpress? I am trying to get a custom field from the postmeta table so that I can display an thumbnail image next to the post title. Help, please.
Wes says...
Hi Rut,

I haven't implemented it into wordpress before, but I imagine it is pretty similar to a standard php installation.

Find your global include file and include the function into the wordpress site. Then use the resize function to wrap your image src just like the documentation states, also make sure you have ImageMagick and your cache folder configured properly.
mores says...
To use with WordPress, I found it to be easier to copy the necessary code into your theme's functions.php and use it to modify the calls to your images.

If you're extracting post images etc it'll be a bit complicated, too much so to post in this little box :)

Right now I'm using it in a wordpress installation that's running in a subdirectory and it fails - must be some path issue.
Jaume says...

Hello, I installed your script and I think I'm doing something wrong, because I do not work either locally or remotely, have given permission (777) to the images directory. If you please take a look at, I've also found that the image is seen in / images / dog.jpg and this is correctamente.Tambien I enclose configuration php / info.php.

Sorry but my English is very low

mat says...
Thx for the script
had also trouble getting remote image too work. finally i discovered that jou just have to add s directory remote in the cache dir..

arif says...
i see lots of people say its a great script.. but i cant use it. learning curve too high.

plz. explain what is imagemagic, what it does. also explain more about the folder/directories - cache?? convert??

i have a temp directory on my c: drive and the 'uploads' folder for storage.
and plz put full step by step inst. for us novice who can then make use of your work.

i need to resize my file ie. reduce it's file size when uploading and saving to my server? can this script do it?
help me and a coffee is coming up your way.

doogle says...
the other day while eating cookies I thought of this script.

then i had to poo
Andie says...
This is a great script... if I wanted to use this to actually resize and then save the new version of a photo, how would I go about it?

Wes says...
Hi Everybody,

I'm sorry I haven't gotten back to some of the issues posted here. Imagemagick is a software suite that runs on the command line. It interfaces with php many other programming languages. More can be learned about imagemagick @

Yes, to get remote images working, you will need to add a folder for remote images in your cache folder, there is a configuration for this in the function if you wish to place it elsewhere.

This script isn't meant to work when uploading the file, but rather when calling it inline on your code. It takes the originally sized photo and resizes it down. So you'd place the code in a 'View' or plain html / php file.

To save a new version of the photo, it should auto detect if the newer photo is "newer" than the cached one.. You can also clear out the cache folder to regenerate all you images again.

Zubair says...
try this ver usefull
Gal says...
Works like a charm! Thanks a lot for this!
@arif - this is not a beginners script so if you have a project in mind and you'd like to use it, begin by reading about what ImageMagick is, and don't complain to the script provider for not having guided hand in hand.
vishnu says...
First of all, this script is very good and it is working perfectly on my server.
But now i'm facing some troubles on it.

On my testing I made a new folder in the root directory and put all required files,folders & images inside it. Then I tested the URL like (, and it was perfect.

Then I tried to implement it on various images on the website itself. This time its showing 'Not found' images. My images are residing in different folders and subfolders but website have a master page, so each and every requests are passing tru index.php, so i made 'cache'(777) folder in the root directory where the index.php residing.

Can anybody help me where is the problem ? any directory structure issues ??
wes says...
Hi Vishnu,

It sounds like your having some kind of path problem to your images. The best method is to use absolute paths to your webroot path.


Something like that should work, just as long as your image is located at that absolute path.

vishnu says...
Hi Wes,

No luck with absolute path too.

Also I wondered by another behaviour.

As I told in previous post, its working perfectly in demo folder (ie;

And then I put all files,folders & images in the root directory itself (ie;

Its showing only one image ( $settings = array('w'=>300,'h'=>300,'scale'=>true);)
and all others not appeared.

Do you know why?
Daniel Mores says...
New project, new server, new problems.
For some strange reason, an external file can be written into the "external" directory, and convert seems to work since the script returns a file name that I can use, but that file does not exist.
I'm not sure where I can start looking for bugs. The directories are, apparently, writeable, and convert must be found or else I would not get a proper file name. Right?
I'm hosted at emerion and the directories are not CHMODable by me, but the tech guys tell me that php scripts can write anyways.

Any ideas?
wes says...
Hi Vishnu,

I'd need to look at the code to see what exactly is happening. It still sounds like a path issue, maybe permissions? Can you post some code up on

Hi Daniel,

Make sure those external directories that you are writing to are writeable by your webserver. In most cases that would be apache. If it is generating the md5 serial hash filename then things should be good, just sounds like a permissions issue. You might want to check your error logs for the site to find some kind of clues.

Daniel Mores says...
Hey Wes,
thank you for getting back to me so quickly.
I don't have access to a lot of things on that host, I can't even use my FTP program's CHMOD function.
The host tech guys said "don't worry about it" and sure enough, a file has been generated in the cache/external directory. Which means that the directories *are* writeable by scripts.
But the files generated by convert are not, apparently.
Can this be?
Wes says...
Hey Daniel,
You might want to make sure you have the correct path to convert. Depending on hosts, sometimes it will just be available as 'convert'.. Or you might need a full path to the function. '/usr/bin/convert'

There are definetely a few things that can go wrong due to configurations of server enviroments. No server is the same :)

I can take a quick look at your configuration / setup if you wanna send me some code.. Email it over to

Vishnu says...
Hi Wes,

I don't think that an issue with path because one of the method is working fine (the scaling one) and the 'canvas-color' method not working.
I tried following code, there are 2 methods (scaling & canvas-color)

First I put this file in root directory itself (www/) there i can see
-First image(canavas-color method) - not showing
-Second image (scaling method) - showing fine

Then put it in another folder in root directory (www/testfolder/) there both images are fine.

So it seems that 'canvas-color' method have some issue when it is in root directory, actually that is what i looking for.

any clues?


include 'function.resize.php';

$settings1 = array('w'=>115,'h'=>60,'canvas-color'=>'#FFFFFF'); ?>
<img src='<?php echo resize('logos/8.jpg',$settings1)?>' border='1' />

<?php $settings2 = array('w'=>115,'h'=>60,'scale'=>true); ?>
<img src='<?php echo resize('logos/8.jpg',$settings2)?>' border='1' />
alex says...

thanks for the script!.

i would like to request a copy of the external image source - resize - cache - use local image copy. i noticed on one comment that is now ready.

thanks in advance.

i would be following this post. :) subscribe to comments plugin is also a convenient feature. :)
alex says...
i have a similar custom script but it seems that my version is too resource hungry and would crash some of my old hosts. I think your version is better than mine! :)
Jobs in jaipur says...
I am getting clear.
Morten Skogly says...
Hi, my host doesn't have Imagemagick installed, only GD. Does anyone know how to convert this code to run with GD instead?
Wes says...
I did have a working version with gd, but have seemed to lost it. Plus its a little out-dated.
Ryan says...
Works like a charm.
I had to modify a section of code because if you crop an image with the width and height not being equal, you'd sometimes get the canvas instead of a proper crop.

I had to add this to the cropping section:
if (($h/$height)*$width>=$w) $resize = ($h/$height)*$width;
else if (($w/$width)*$height>=$h) $resize = "x".($w/$width)*$height;
Stacey says...
This an awesome script! It is great to be able to pull from remote images. My question: Is there any way to not have the canvas show up? With the canvas, vertical images have extra space on the left and right and horizontals have extra space on the top and bottom. I want to set a maximum width and height, but I don't want to end up with the extra canvas area. Does that make sense?
Jamille says...
in case you are having troubles... filepaths extremely important, of course.
Wes please confirm this is accurate...
$cacheFolder is from the document root of your server.
So is the url of the image itself, only the script checks this for you, not for $cacheFolder though, you need to specify this literally, so if your image is here:, then this is your literal path: $_SERVER['DOCUMENT_ROOT']."/img/image.jpg".

$path_to_convert , as reported above is very different on many servers. If you dont have direct access to your account you can do the following in php, assuming 2 things: Image magick is in fact installed somewhere, and you do have eval() rights turned on...
try this in php:
eval('whereis convert', $output); echo var_dump($output))
This was the only way for me to confirm I had the right path to the imagemagick libs.
shivani says...

I am using xampp.

how did I know my cache folder and path to convert?

Chris says...

I am trying to get this to work with the image url populated from database info, i.e

<img src="<?=resize($linkdir . $uploadfile_bground, $resize_settings)?>" alt="" />

This doesn't seem to work, however works fine when hardcoding the image url into it as in below...

<img src="<?=resize('/uploads/image1.jpg', $resize_settings)?>" alt="" />

Im sure theres something I'm missing, but can't find what
wes says...

u might want to concat the variables prior to sticking them in the argument.. ex:

$filepath = $linkdir.$uploadfile_bground;

also debug that variable to see if its the correct path to your files. otherwise it should work

Chris says...
Hi Wes,


I have tried that, and although something is now happening, I don't know that this has been the cause.

What I am now seeing is that certain images are being resized and will show on the page, whilst others arent.

I am getting a cacheed image location load into the src for the image, but there isnt anything actually within the cache folder for that image.

Its odd as it does work with some images.

I have tried various image types, but that doesnt appear to be the cause, as it is working for each image type, just randomly.

Any ideas?

THanks again
wes says...

Are all the images the same size relatively? same dpi at least? Its possible ImageMagick might be choking if the images are too large.

You should see temp images building into your cache folder. If you don't see any images added into your cache folder then you might be experiencing another problem. I'd need to see more code examples to help much further..
priyank says...
I tried this script but It is not working there is some problem to create a image in cache folder.
Chris says...
Hi Wes,

Got it sorted, well no idea how I did, it just seemed to work. Perhaps it was as you say something to do with the size of the images, as some of them were 6m!!

I have just limited the size the gallery will take during the upload, which will prevent this.

I have another issue now however, I am trying to deploy this onto a wamp machine (2003). I've got imagemagick installed, but seem to be having issues determining the path to convert...

I have: C:\Program Files\ImageMagick-6.6.2-Q16\convert.exe

however am getting the error below when trying to load my page.... (Incidentally this worked 100% on my linux test box).

PHP Warning: exec(): Unable to fork [C:\Program Files\ImageMagick-6.6.2-Q16\convert.exe 'uploads/7-DSC02203.JPG' -resize 80 -size 80x50 xc:transparent swap -gravity center -composite -quality 100 cache/d41d8cd98f00b204e9800998ecf8427e_w80_h50_cp.JPG] in C:\Inetpub\Websites\intertech\www\Scripts\function.resize.php on line 107
Chris says...

Solved this one, I had the path to imagemagick right, however if on windows you need to give IIS permission to execute scripts using the cmd shell.

To do this open up a cmd window (Start>Run>cmd) and enter the following command (You can copy and paste.....


Hope that helps someone :)
Thomas says...
I have tried the script and it works great! Only it gives errors on some occasions. If the image file is

It does not work. Maybe it is because there is no .jpg? o .gif extension?
wes says...
Hi Thomas,
Yes, thats probably the problem your having, you should have the extension in your filename.
Thomas says...
Hi Wes,

I am using your script, but when i resize, sometimes images are not resized proper. I can only see a part of the image..
wes says...
what settings are you using to resize the image? and what is the original image size?
buthas says...
no consigo que funcione, en el example.php no sale la imagen externa (http://....) sale una imagen en negro.


y en caso real me sale este error: "Cannot redeclare resize() (previously declared in /homepages/4/d284870012/htdocs/pc-teros/carrusel/function.resize.php:9) in /homepages/4/d284870012/htdocs/pc-teros/carrusel/function.resize.php on line 120"


¿me pueden ayudar?
wes says...
I'm sorry I don't fully understand what your asking, although when I saw the redeclare error message, it sounds like your including the php resize function more than once on the site?
Denise says...
Yay! I'm the 4,030th download. =D

Can't wait to try it.
Thomas says...

Some images are correct but then some are not resized correctly
Thomas says...
The original image size w: 460 * h: 580
buthas says...
Thanks for your answers.
everything is solved. and is working perfectly here:


thank you very much for the script.
buthas says...
How I can fix this to work on a server that does not allow exec ()?

if(isset($opts['scale']) && $opts['scale'] == true){
exec($path_to_convert." ".$imagePath." -resize ".$resize." -quality ".$quality." ".$newPath);
exec($path_to_convert." ".$imagePath." -resize ".$resize." -size ".$w."x".$h." xc:".(isset($opts['canvas-color'])?$opts['canvas-color']:"transparent")." swap -gravity center -composite -quality ".$quality." ".$newPath);

exec($path_to_convert." ".$imagePath." -thumbnail ".$w."".(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "")." -quality ".$quality." ".$newPath);
exec($path_to_convert." ".$imagePath." -thumbnail x".$h."".(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "")." -quality ".$quality." ".$newPath);
wes says...
you can try passthru rather than exec.

or system might work depending on your server.

rather than






buthas says...
thanks for your reply, the function "passthru" is disabled in the server That can also, but apparently the function "system" if it is enabled. Now I have no errors, but the image is not generated. out <img border="0" src="./cache/f743792d8131433699316814a9e23852_w90_h128.png"> but the image is not in the folder. / cache but if the images are original ./cache/remote


buthas says...
do not worry, my server support, told me that you can not use any of these functions. and only you can use the GD library.

know any script to do the same as this, but only using the GD library functions.

thanks for your help and your time.
Thomas says...
Hey I still have some questions about your script.
If I resize the picture to 240*160 it cuts out the center part of the picture. What if I want to resize but keep total picture?
Wes says...
Hey Thomas,

You should be able to use crop=>false,scale=>true..

I believe that will solve your problems.
manuel says...
Hi, great script, really, simple and useful.
Just a question: is possible add a watermark to images after they are resized?
Thank you
Thomas says...
exec($path_to_convert." ".$imagePath." -resize ".$resize." -size ".$w."x".$h." xc:".(isset($opts['canvas-color'])?$opts['canvas-color']:"#FFFFFF")." swap -gravity center -composite -quality ".$quality." ".$newPath);

Hi wes using scale does not fix it because then it only resizes from one side. What I want is a complete picture resized to the proportion needed and add whitespace if needed, hope this makes sense to you?
wes says...
Hey Manuel,

You can add watermarking into this script fairly easily.. Check this out:

You might need to tweak folder paths and such..

Hey Thomas,

If you take a look at the demo page, it has the same example your looking for.

I believe you'll want to only define width and height for your resize.. This will resize and add canvas space around the image.. you can also define the canvas-color.. If your using png's I think the canvas should be transparent by default
manuel says...
Thank you wes. You are very helpful! I used another script for the watermark, but your script is really useful and versatile. Compliments.

To return the favor...
@Thomas (and @wes, if you accept the suggestion or if you have improvements to do ...I'm just a poor web designer...).

Like Thomas I wanted to resize images but keep total picture, so I changed this part of your script:

if($create == true):
if(!empty($w) and !empty($h)):

list($width,$height) = getimagesize($imagePath);
$resize = $w;

if($width > $height):
$resize = $w;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = "x".$h;
$resize = "x".$h;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = $w;

with this:

if($create == true):
if(!empty($w) and !empty($h)):

list($width,$height) = getimagesize($imagePath);

$rw = $width / $w;
$rh = $height / $h;
if ( $rw > $rh ) {

$nw = round( ( $width / $rh ) );
$resize = $nw;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = "x".$h;

} elseif ( $rh > $rw ) {

$nh = round( ( $height / $rw ) );
$resize = "x".$nh;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = $w;
} else {
$resize = $w."x".$h;

I hope that this will be helpful, or at least not without a sense ;-)
Syko says...
Thank you for the script, saved me a lot of time making it, really good job, works flawless. Regards
Adam says...
I used your script to resize & crop some images on the front page of my website however while most of the images get cropped without a problem some of the images appear to get a black border at the top and bottom:
Tony C says...
So there was a problem with the remote cached images being repeated.
On my site, I link pictures from external sites. A lot of the time, the end file names are similar (such as 01.jpg, etc.)
The function seemed to cache the remote image, and use that image over and over, regardless of the file path before the end file name.

To fix that, replace:

list($filename) = explode('?',$finfo['basename']);
$local_filepath = $remoteFolder.$filename;


list($filename) = explode('?',$finfo['basename']);

$file_temp_add = str_replace('/', '_', $finfo['dirname']);
$filename = $file_temp_add."_".$filename;

$local_filepath = $remoteFolder.$filename;

Not a great fix, as it makes the cached file names look crazily unorganized, but your images will now all show if they are using the same file name! :)
Ryan says...

This is a fantastic script you've got here. I have it installed on my website, yet i'm having a few troubles.

I am sourcing images from an external URL and not locally. The script is doing it's job perfectly and putting these external images into the 'cache/remote/' folder, however, when viewing the website and what should be the resized images - the images do not show.

The image source is pointing to 'cache/whatever.jpg', and when i checked, there are no resized images being written to the cache folder.

shanee says...
Great job, A true script for handling different resolutions
Muhammad Fahad says...
Hi Dear,

I download the files and try to run on my local machine But its not working. i have WindowsXP XAMMP Latest Server.

Please Help !


Muhammad Fahad says...
Hi ,

i have this code which is not working. please Help!.


function by Wes Edling ..
feel free to use this in any project, i just ask for a credit in the source code.
a link back to my site would be nice too.

function resize($imagePath,$opts=null){

# start configuration

$cacheFolder = './cache/'; # path to your cache folder, must be writeable by web server
$remoteFolder = $cacheFolder.'remote/'; # path to the folder you wish to download remote images into
$quality = 90; # image quality to use for ImageMagick (0 - 100)

$cache_http_minutes = 20; # cache downloaded http images 20 minutes

$path_to_convert = 'convert'; # this could be something like /usr/bin/convert or /opt/local/share/bin/convert

## you shouldn't need to configure anything else beyond this point

$purl = parse_url($imagePath);
$finfo = pathinfo($imagePath);
$ext = $finfo['extension'];

# check for remote image..
if(isset($purl['scheme']) && $purl['scheme'] == 'http'):
# grab the image, and cache it so we have something to work with..
list($filename) = explode('?',$finfo['basename']);
$local_filepath = $remoteFolder.$filename;
$download_image = true;
if(filemtime($local_filepath) < strtotime(' '.$cache_http_minutes.' minutes')):
$download_image = false;
if($download_image == true):
$img = file_get_contents($imagePath);
$imagePath = $local_filepath;

if(file_exists($imagePath) == false):
$imagePath = $_SERVER['DOCUMENT_ROOT'].$imagePath;
if(file_exists($imagePath) == false):
return 'image not found';

if(isset($opts['w'])): $w = $opts['w']; endif;
if(isset($opts['h'])): $h = $opts['h']; endif;

$filename = md5_file($imagePath);

if(!empty($w) and !empty($h)):
$newPath = $cacheFolder.$filename.'_w'.$w.'_h'.$h.(isset($opts['crop']) && $opts['crop'] == true ? "_cp" : "").(isset($opts['scale']) && $opts['scale'] == true ? "_sc" : "").'.'.$ext;
$newPath = $cacheFolder.$filename.'_w'.$w.'.'.$ext;
$newPath = $cacheFolder.$filename.'_h'.$h.'.'.$ext;
return false;

$create = true;

if(file_exists($newPath) == true):
$create = false;
$origFileTime = date("YmdHis",filemtime($imagePath));
$newFileTime = date("YmdHis",filemtime($newPath));
if($newFileTime < $origFileTime):
$create = true;

if($create == true):
if(!empty($w) and !empty($h)):

list($width,$height) = getimagesize($imagePath);
$resize = $w;

if($width > $height):
$resize = $w;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = "x".$h;
$resize = "x".$h;
if(isset($opts['crop']) && $opts['crop'] == true):
$resize = $w;

if(isset($opts['scale']) && $opts['scale'] == true):
$cmd = $path_to_convert." ".$imagePath." -resize ".$resize." -quality ".$quality." ".$newPath;
$cmd = $path_to_convert." ".$imagePath." -resize ".$resize." -size ".$w."x".$h." xc:".(isset($opts['canvas-color'])?$opts['canvas-color']:"transparent")." swap -gravity center -composite -quality ".$quality." ".$newPath;

$cmd = $path_to_convert." ".$imagePath." -thumbnail ".(!empty($h) ? 'x':'').$w."".(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "")." -quality ".$quality." ".$newPath;

$c = exec($cmd);


# return cache file path
return str_replace($_SERVER['DOCUMENT_ROOT'],'',$newPath);


Mayur says...
I am building a simple photo gallery in php and need auto image resize script. So all the image names are coming out of the database through a while loop and all the images are stored in a gallery folder while uploading.

So how to implement this image resize script there? I tried but the images wont show. I am confused about the paths and not sure exactly how this script works. Where can i find instructions?
Artificial Colours says...
This script is amazing, can believe how well it works!
Not just the image resizing, but having all user uploaded images on a site, the same size with cropping is spot on! Thanks!
Al says...
I get no images and on the last item I get:

function.file-put-contents]: failed to open stream: No such file or directory in /virtual/users/e15975-16956/web/resizer/function.resize.php on line 40
image not found' border='0' />

Image cropped & resized by width and height from a remote location.

Any help is appreciated, thanks!
Sush says...
Hey Wes,

I downloaded the code from your site... But sadly its got some sort of an error..
The imgaes are not being cropped or resized.
I also checked using fire bug, The "src" attribute of the img tag has a value.... but the images dont show on the browser...

Please help me out.
Sush says...
I am facing the same problem Al is facing... but in my case, the image is being downloaded on to the cache folder but the resized version of the same doesn show up on the page.
Sush says...
Hey Wes,

The i tried the code on my server... i works fine... I guess i had some problem running it on xampp. But its a pain if the gallery is huge and has images which weigh more than 600 kb... It takes a long time to cache...

Please let me know if you have a fix
Wes says...

Have you checked your full file path to see if its an accurate path to your file that you are wishing to resize? It looks like that might be your problem.


If the images are over 600k, and taking a long time, that is really an issue with ImageMagick, as that is the core library that crunches and resizes images. You could look into optimizing ImageMagick itself, or pre-optimize the images that it is resizing, although once images are cached and resized, it really shouldn't take long to pull them again, its just the one time resize that takes a while.

I hope this helps you both, thanks and happy holidays to everyone
Eddie says...

The script works and then stops sometimes.. the src to the resized image get populated but the file does not exist in the cache directory.. does not happen all the time though.. Thank you in advance!
Mariusz says...
Why didn't you use ported to PHP IMagic static class? Are there some troubles with this class? Maybe memory issues?
Van says...
I just installed the script in project where visitors upload pictures of their artwork and I want to display them at a reasonable size on screen. I want to maintain the aspect ratio, so just setting "array("w"=>250)" works perfectly. Until someone uploads an image that is only 180 wide, then I don't want it blown up, I just want to see the 180xwhatever image. In other words, I want the scale factor limited to 100%.

Can this be done?

Lars says...
Is there anyway to check for extension: jpg or gif from remote external server.
And if not jpg or gif it shouldent download to remote folder?

Another thing! is there a way to show noimage avaliable if there is not a image on the external address. Thank for this great script. It works great.
Craig says...
Hey Wes,

Awesome script, got it working fine!

Is there a way it could be modified to clear the cache after a certain amount of time?
sixtillnine says...
First off, great script. I'm new to php and managed to get it up and running.

The script works fantastic for portrait images, however if I upload a landscape image, the image is resized to the correct width then stretched out of proportion to the correct height - rather than the extra pixels required being added to the canvas.

Is there a fix for this?
sixtillnine says...
Sorry let me clarify, the image was not being stretched.

However the pixels were not added to the top and bottom of landscape images to increase the canvas size to the height value specified on landscape images.
osagie ben says...
this thing is not working
GalaxyTramp says...
Great script! I have a problem though. I need to resize images from this type of URL:

As you can see no image type suffix. Can this be done using your script??

To those who say this is not working, check your paths are correct and ensure that you have imagemagick compiled on your server. It does work and very well!!
Ankur Pandey says...
Wes !! Man
u r great. I implemented ur script in Magento for my custom requirement & u know what it requires no changes u rocks !!
Nick Coppins says...
It's possible to easily alter this script to generate thumbnails from PDF files.

I simply changed:

$ext = $finfo['extension'];


$ext = "png";

To force the ImageMagick convert command to output PNG files, regardless of the input type (as long as it is support, which PDF is).

daveydoodoo says...
Great script, got it all up and working, having one issue.

In some of the images the black gets dropped. Any ideas on why?
naresh says...
hi i download the script but it didn't work which is the cache folder please help me
josh says...
it would be great if there was better documentation about working with absolute paths. really struggling to make it work with my directory structure.

function in

calling page in

images in
Fideri says...
If you have issues with input filenames that contain spaces, the simple, clean and safe solution is to wrap the escapeshellarg function, eg
$cmd = $path_to_convert." ".escapeshellarg($imagePath)." -resize ".$resize." -quality ".$quality." ".$newPath;
Peter says...
The scripts works like it should. I have it working on my picture gallery software. However, it is very slow. I have tried it on both Windows and Linux on various hardware and the speed is the same. If I open a page that calls for 20 pictures within the same directory, it takes a about 20 seconds to generate and display them. These are pictures who are approx 3456 x 2304 and around 2MB each.

Is this slow speed expected due to the original image sizes or is there something I can do to improve this? Or is Imagemagick not the way to go for me, as in, should I already have smaller sizes on the server? Was hoping having one version and quickly serve the user with a smaller version on the fly.
Emanuel Coelhoq says...
Hey guys,
I've been having some problems with the spaces in the images or folders names but i solved it with a single row.

Just put this row:
$imagePath=str_replace(' ', ' ', $imagePath);

Just before:
$purl = parse_url($imagePath);

It should be around line 23 of the php script.

Peter says...
What I also have noticed is that if the user uses a Windows machine, the scripts kills ImageMagick after just a few images. I have to restart the webserver before it works again. If I use a Linux machine, I can browse to my hearts content. Very odd since this all happens on the server and the client machine should not matter at all.
Arslan Qamar says...
Friends I am facing this error so please some one help me to solving this issue....

function.file-put-contents]: failed to open stream: No such file or directory in D:\www\function.resize.php on line 40
image not found' border='0' />
Sunil says...

Script of demo (Online) is really nice but
this is not work for me. Image is not display, please help me.......

Zeus says...
hey there,

same problem here as for some guys around...

the script is up, the image file is up as well, however it won't generate the cache files...
i have added this one for the cache folder
$_SERVER['DOCUMENT_ROOT'] . '/cache/';

also, i have created a directory called remote inside the cache folder.. what happens after i run the script, is that it creates the cache of the remote file, but not of the local file stored in /images/

it gives me the it's path

which is unavailable...
any idea on this one?

thanks in advance!
salim says...
very good
Anand says...

Used this script but not generate the cache file .cache folder permission is 777.Just display below cache image path but not actual image is generated in cache folder

Eric says...
Just in case anyone else had the same problem - I wasn't able to get the script working with just a height variable - I got an error stating that $w wasn't defined. I changed the last bit of the code and everything is working as expected: (this is right before the command is executed - $c = exec($cmd))

$cmd = $path_to_convert." ".$imagePath." -thumbnail ".$w."".(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "")." -quality ".$quality." ".$newPath;
$cmd = $path_to_convert." ".$imagePath." -thumbnail x".$h."".(isset($opts['maxOnly']) && $opts['maxOnly'] == true ? "\>" : "")." -quality ".$quality." ".$newPath;
Amit says...
I am not able to resize the image.Could you please tell me teh requeriment to work this script.I very munch sure for imageMagick is not installed other then that?
Paul says...
I am having issues when resizing an image of 600x850, down to limit of 200x300.

There should be space added to the top and bottom, however, the script is chopping off the side of the image, which suggests it is scaling the image to the height limit.
Paul says...
Nevermind, I fixed it :)

Set crop to false and cleared the cache folder.
Ajay says...
I have added the code that you have given, the only problem I am facing is that the image that needs to be add in the cache folders are not getting added. Please help me out.Thank you in advance
Chris says...
I've chmoded the directories to both 755 and 777, neither have worked.

It downloaded into the remote folder, but didn't convert. I've configured all paths correctly. I've tried both scale and crop settings.

Any suggestions would be extremely appreciated, this is an awesome script for a newbie like me.
Peter Molnar says...
Many thanks for this snippet. You save hours from my life!;-)

I can convert on server side 4000 picture (not on-the-fly, but with small modification your php was great to convert into a folder).

Thx again.mP
Sujit Mourya says...
How do i pass parameterized variable to the url in function resize("$imagefile",array('w'=>300,'h'=>300)); i am using $imagefile to pass value from url when register globals is On. using same way i want to pass width and height like
Please help!
Chris says...
Don't bother posting a message, he's not looking into this anymore.
Vovanys says...
Thank you, cool stuff!
David Ruiz says...
Great script! I tried a few others that were also great but yours is so light and does what it does well.

Thanks for sharing.

neil says...
Hey man thanks a lot for this work, its probably going to help me out a lot. One question if you have the time, do you know how i would use this script with a BLOB from mysql. im doing the seperate php file for retrieving blobs and since its not a direct link to the .jpg file and instead a link tha tlooks like thisimg.php?id=2, i dont think your script will take it as a path.

any ideas on how to work around this?
LovinIt says...
It seems the cache folder will simply grow and grow... how can we purge the cached file and replace it or keep it from being full of stale and invalid thumbnails?
Wes says...
Thanks to pale purple on github, some much needed updates we're pulled to this script.

Peter Molnar,
Thanks, glad to hear its cranking away on that many pictures :)

Sujit Mourya,
Sounds like you just want to put your resize function inside the <img tag.
The example.php file should help you with the code you'll need

Its true, i've been busy with other stuff, but I do check back periodically, and do my best to help. The new script changes by purple pale should help you diagnose the path problems.


Thanks for the comment.. Glad to hear its working for you.

I'm not too sure about the BLOB from mysql, my guess is to generate the tmp file and then convert it to the blob type into mysql and remove the tmp file. I haven't messed with mysql blob types very often.

Most of the time cache folders don't grow too big, but if you do have a massive amount of images, you'd probably want a cronjob that checks file time and clear out the old stuff..
Wes says...
Thanks so much for the script. Only had to change the path to ImageMagick, and it was rocking and rolling. Well done. Thanks!
Marcel says...
Works like a charm! Re-rolled many projects from timthumb to this, thanks a lot :)
Robin says...
Hej Wes

I just copy pasted the example and the other files, all my dirs are 777 but the function doesn't return anything.

Did somebody had a similar problem?

Gerry says...
Great script! Though, I am having issues making it work with remote images.

My remote folder is writable. And the local files convert without any issue.

Remote files, however, return the following error:
Tried to execute : convert './cache/remote/2934973285_fa4761c982.jpg' -resize '100' -size '100x100' xc:'transparent' swap -gravity center -composite -quality '90' './cache/d41d8cd98f00b204e9800998ecf8427e_w100_h100_cp_sc.jpg', return code: 1, output: Array

Any ideas as to where I should start looking?

Many thanks!!!!
Marcel says...
Robin, if you copy/pasted the codes directly and it doesn't return anything the only issue might be that you didn't include it in the php page. Make sure you have something like:
include 'thepath/function.resize.php'; on top of the php page.

Other than that the issue might be the convert path, but a fault there should still return something.
Make sure ImageMagick is installed and change $path_to_convert = 'convert'; to the proper path, like /usr/bin/convert
13ankster says...
useful script
glen says...
installed imagemagick put the path in .. and still no go. cannot even get the images to show up... even the one that is linked to flickr? I can copy and paste that url in and get to the image.. but will not pull up in the example page... have tried relative and absolute paths.

Think this will be killer if I can get it working.
glen combe says...
ok. I dont usually answer my own posts.. but after 4 hours of time I figure I can save some gentoo server users some time.

1. build imagemagick by doing this or at least verifying what it supports.
USE="-*" emerge -pv imagemagick add the desired things you want to support but make sure to add jpeg if its not highlighted green.
2. change the convert path in function.resize.php from 'convert' to '/usr/bin/convert'.
3. Since Gentoo is bleeding edge make sure to change open short tags to your php.ini to On. they default to off I believe as of php 5.3
or change all the short tages <? to this <?php
4. add a closing "?>" to the function.resize.php file at the very bottom (its missing)
5. if you create the cache and remote folders per the mesage you get and do the above other steps should work great on a gentoo install of php and apache.

Steve says...
Great script, but how can i get rid of the black bars on the side when cropping? I also have the problem that the cache file is not written if I try a $settings = array("h"=>84). Any solutions for the two problems?

Julian says...
This is an awesome script. We are using it in our website.

@Adam. In order to remove the top and bottom black border, you'd need to pass "scale" => "true" as an option.

Alternatively, I wanted to comment that you can also force to convert from PNG to JPG (and save space) if you add a line in the script code to capture the jpg extension from $opts and then set it to the output.
Nhik says...
sir/madam I am a beginner of web programming can you give me a complete code of resizing an image that when you click the image the original size have been converting into a smallest,so pls.. help me an give me a code of it complete code an their index that I include to test it sir/madam ,thank you hope you can help me today
Phillip Ebanks says...

I've been using the script on a few websites and it works likea charm, super easy to use and really think this is a great class.

My only problem is when working on a localhost (xampp mac OSX Lion) the code wont work since imagemagick is'nt installed by default.

Do you have any help you could provide with setting up XAMPP - Mac OSX with ImageMagick.

I've been going trough documentation about installation and can't seem to find any dtailed enough to take me trough the whole process.

Thank you for your help
Edi says...
It's not work for me. I used Xampp 1.7.3 as my local server. Image still blank, and not create the cache image. What should i do??
parvez says...
Nice info.
Adam Harness Design says...
Thank you for this tool! It saved me HOURS on a website I'm developing for one of my clients! I plan on using it for other projects as well.
James says...
Hey, thanks for the neat script :)

Maybe someone can help with a problem â I'm using the script within a Wordpress sidebar widget... the image is being added to the cache folder fine, but the src on the page is blank.

It's being called like this:

$output .= '<img src="' . resize($photourl,$settings) . '" border="0" alt="' . $linkurl . '" />';
Wes says...
@Phillip: Thanks! I appreciate the comment.

@Phillip, @Edi:
To get imagemagick working on XAMP / MAMP, you'll need to create the binaries, then control the path to the binary files in the exec section of the script.

@Adam: Glad to hear its working for you, and you'll be using it in the future too!

@James: What is your source code look like? Is there an error in the src=''?
bernte says...
@ author .. maybe you can add this to the example ..
<?php passthru('which convert'); ?>
it shows you the $path_to_convert ...

i had some problems with the script on different servers and was wondering why it doesnt work on the second.
the phpsnippet was blank on the 2nd server
Jim says...
Excellent script!
imran says...
hi wes this is imran i am trying to make
thumbs using ur script but example page is not working plz tell me how can we install imagemagick ............
Nidhin says...
re sizing is not working for this image

" "
can you please help to find out what is the issue ? and how i can resolve the issue

classified ads says...
Thank! work for me
Mathijs says...
Is it possible to resize an image by height only ?
Jis says...
Hi, In my server doesn't have ImageMagic installed. Only GD support is enabled. And i am trying to resize external images. Can you please let me know how to do this.
Steve Woodson says...
Great script, one issue I was having is that it would fail on images with spaces in the image path. what worked for me was replacing the first line in the function to

// $imagePath = urldecode( $imagePath );
$imagePath = str_replace(' ', ' ', urldecode( $imagePath ) );

After that it worked great!
Rutwick says...
Hi Wes,
Thanks for the awesome script. I have a little doubt, how do I save the resized image? I need to pass it to further functions for processing. Been trying a lot but couldn't figure out how to save the new resized image in a particular folder.

Please help man!

karn says...

i use this code but no image display at example.php page so what we do
please help me
federico says...

i use this code but no image display at example.php page
I checked the script and I noticed that you do not create any image in the cache folder (I set the privileges to 777)

please help me
Auke says...
Hi, great script man! I am just wondering if it's possible to use this script with loading an image path from a table in a mysql database?
Eric says...
Thanks for the script. I have a question about one of the resizing examples on 'resizing3/examples.php' page.

[w] => 300
[h] => 300
[scale] => 1

The image shows white bars on both sides. Shouldn't the image just resize without added canvas around it?
Eric says...
I fixed the "scale" problem mentioned above by changing the identical operator (===) to equal operator (==) on line 125:

if (true == $opts['scale']):

and it works fine now.
Kevin says...

Would you please tell how can I get it run on Windows? I have installed ImageMagick.

From the output, it seems the parser did not recognize the function (resize) call: there is a broken link icon followed by ' border='0' />
dilshan, says...
It is not resizing but cropping as per your demo the image is getting cut it is not resizing/shirking.
mike says...

I'm using your script for 2 years now. I just notice that it's not resizing nor cropping anymore when I updated my PHP. What seems to be the problem?

Marc says...

First of thanks for this great function! I have one question though:

I do see the images come up in the cache folder, and they do load faster because i cloack them from external websites. The only things it doesn't do is resize the images when it saves them. I only specify the height like this:

$settings = array('h'=>200);

What could be the problem here?

Thanks in advance!
Marc says...
Let me just answer my own question here. I tried it with specifying width as well and now it resizes.
GC says...
The script is awsome, the examples also....
But it doesn't work on my server. I've set the cache it downloads the remote files into ./cache/remote ; but sadly it doesn't make any resized photo... the cache folder is always empty and the function does not return any path :(

Do you have any idea what can be wrong?
Don says...
How can I remove the black color at the background. I noticed that when I resize some images, it will have a black background
abhishek gahlot says...
Your code break when ever the file name is something like img...jpg

Can you tell me what could be the way to solve this.
Reggie Escobar says...
Doesn't work. Doesn't automatically create cache/remote dictionary. Should save the cache file using some random generated hex code. I have a picture called cover.jpg but in different dictionarys and it only caches 1 cover.jpg image. since like i said... if you have 2 images with teh same name but in different dictionary, it will only show one imgage.. the other image won't appear
M says...
Great script! Exactly what most of us need! With the addition of this piece of gold my website gained more or less 30 points on Google's Page Speed. Really great!
kiko says...
is there anyway to select a specific area of image?
Kuldip says...
Not working for me.
I have image magic enabled.

I have just placed into one folder and run. But no result.
Jason says...
Is it possible to have the same function running on gd2 instead of imagemagick?
soundar says...
Great Script, But not working in window system. Plz help me...
Mark says...
A brilliant script, working very nicely (once I had my host install imagemagick)

Question: is there a way I can generate images without specifying a width. I would like to be able to specify height only, in the same way as one can specify width only and the height is proportional.

Can this be done?

It would be very useful for occasions where height is the constant, and width is potentially variable. In this case, creating a scrolling horizontal bar of thumbnails.

Thanks again.
leslie mash says...
I give me this error: Notice: getimagesize(): Read error! in C:\wamp\www\wes-phpimageresize-3ff3e32\function.resize.php on line 109
Deanna Satre says...
I had to move my site to a different server and the script seems to have broke. ImageMagik is installed and the permissions on the cache file is set. Any ideas?
Robert says...
For height only change


" -thumbnail ". (!empty($h) ? 'x':'') . $w ."".


" -thumbnail ". (!empty($h) ? 'x':$w) . $h ." ".
Mark says...
Fantastic script, a real time-saver. Thank you!

Question: How would one go about adding the '^' flag to have resized images cover the entire size of the new canvas (without any added background colour or transparency).

Maybe it would be good to have this added as a new option ('fit'=>true) ?

I had a go at editing the code myself but I don't know what I'm doing.
Bolek says...
It's not working in localhost. What should I change? ... path or something else to work propertly localhost
Jack says...
How about performance? on a website with lots of image and lots of visits.
Vikas says...
its working properly but not showing images of dog except last image
Brian says...

Awesome script!
Not sure if anyone is still watching this thread, but I was wondering it it was possible to use this script without the resize option.

I have several remote thumbnails that I would like to pass to the script for caching purposes only, no resize. I have tried leaving the W and H blank, as well as removing the parameters completely from the function, so far all I get back is an empty image. It looks like the value for $W cannot be empty.

Any tips on how to get this script to cache images only would be greatly appreciated.
Brian says...
I just figured out how to cache images without the resize. It was a quick little fix, basically preventing imagemagick from performing a resize by omitting the resize commands.

Around line 138 in function.resize.php
$cmd = $path_to_convert." " . escapeshellarg($imagePath) .
comment out the following line:
// " -thumbnail ". (!empty($h) ? 'x':'') . $w ."".

Hope this helps anyone else who would like to use the script for caching only.

Best Regards

jam says...
it is not working. it is return empty value. please help....
Smartyscripts says...
nice script, I like your script very much, so I did create a smarty plugin with some newer options and is working nice thank you
Yasir says...
it is not working. it is return empty value. please help
web design sri lanka says...
very helpful, Thanks.
Pablo says...
Hi, i'm trying to use your image resizing script but it fails to create image inside cache folder.
cache folder is 777, images is created at remote folder, also 777.
I have uploaded your demo files to but it fails to create and show images.
Also, you can take a look to server error log file at
Can you assist me or tell me what is worng?
Best regards.


Use (Gravatar) for your avatars.