So, you want to resize an image in PHP? PHP Image resizing has not been so easy especially to newbies so let’s make this as simple as possible. All you have to do is save the script below to a file named ‘imgsize.php’ and give it a try. I use it myself on some of my projects and I wrote the script myself. Some usage examples are listed below after the script.
Click here to VIEW SOURCE CODE. Save file as imgsize.php.
Usage examples:
Resize an image to 25 x 25
imgsize.php?w=25&h=25&img=path/to/image.jpg
Resize an image to 50% the size
imgsize.php?percent=50&img=path/to/image.jpg
Resize an image to 50 pixels wide and autocompute the height
imgsize.php?w=50&img=path/to/image.jpg
Resize an image to 100 pixels tall and autocompute the width
imgsize.php?h=100&img=path/to/image.jpg
Resize to 50 pixels width OR 100 pixels tall, whichever resulting image is smaller
imgsize.php?w=50&h=100&constrain=1&img=path/to/image.jpg
Now enjoy yourself!
Questions, comments, suggestions? Post them below.
P.S. Here’s a user (Brian Marshall) contributed set of instructions on how to use the script. – Read it.
Hi,
I would like to use your security image script that you are using for your site below this form. Its looks great. Could you please send me that if possible. Because it looks so cool.
I would really appreciate for your help.
Bunny.
Hi Bunny,
I wrote about that security image script here. It’s a Wordpress plugin though.
http://articles.mikelopez.info/2006/02/09/preventing-comment-spam/
A friend of mine – Benj Arriola, also wrote a similar script which runs independently. It uses PHP Sessions and MySQL though. I’ll try to ask him about it.
Mike
The image quality is awesome, love this script – thank you!
I need something exactly like this that will also resize gif images. Any suggestions?
HI Terry,
GIF support can be added if you compile the GD library with GIF support. I think it’s disabled by default because GIF is proprietary or something like that.
Mike
I do have GIF read and create support in GD, but I’m just not getting this to work. I should note that I’m not a php or script guru by any means, so please don’t laugh at my brilliant attempt:
I basically took your script and hacked around in it by adding this:
$im = ImageCreateFromGIF ($img) or // or GIF Image
The warnings I’m getting are:
… is not a valid JPEG file
… is not a valid PNG file
There’s another script I can use that has no problems with displaying gif, but you have to assign it a width to display. I’d rather work with percentage reduction (like yours does perfectly).
Hi Terry,
You can suppress the warnings by putting @ before each ImageCreateFromxxx call so that it becomes:
$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG or PNG, then show a blank image
I will update my script for that now.
Mike.
Ok, script has been updated to include GIF. However please note that GIF support requires that the GD library be compiled with the GIF support.
Ciao!
::awesome::
This works perfectly. Blogging about it now.
Thanks very much for your help Mike
.
No worries! My pleasure!
Very cool script! Keep up the good work!
Hi Mike,
Nice script, I got one small problem though. It shows gif’s ok but the background’s are black, any workaround this or is this something on my end? jpegs show fine.
Regards
Brett
Hi,
The script is awesone.
Can i give URL in a place instead image absolute path.
For example:
imgsize.php?w=25&h=25&img=”http://example.com/test.jpg”
Thanks
Mazin
Brett,
I think it’s because the GIF you are trying to resize has a transparent background. But not sure. I’ve already found a workaround for this but don’t have time to make it yet. The workaround is basically the one mentioned here:
http://forums.devshed.com/showpost.php?p=1441684&postcount=2
I’ll try to update this next week.
Mike
Mazin,
I haven’t tried that yet but you can give it a try and see if it works. if it doesn’t work, then I suggest that you download the image from the URL to some temporary folder that can be accessed by the script instead and use the temporary image to generate the resized image.
Mike
Just a quick note to Mazin, I’ve tried this for offsite images, and yes you can definitely use a web url instead of absolute paths onsite. Works slick!
This is brilliant, and about a thousand times easier than anything else i’ve found/hacked up to use.
I have, however a question.
I wish to create a function of the whole thing for use within a script. Which I have, and it works fine, provided there’s nothing else there to conflict with the header. simpling having it return gives you back the actual source of the jpeg, which (as you could imagine) is pages of gibberish. Is there a way to return from the function the file in image/jpeg type without using header()? Because I am flat stumped.
Thanks so much,
Conner
Hi Conner,
I’m not sure if I got your point.
If you’re planning to call the function from within a page where othe content is displayed, then it won’t work. Images are external stuff in HTML and cannot be ‘embedded’ into a page.
Mike
Mike,
Great script and thank you for making it for the general public. My question is this: when I use imgsize.php?percent=25&img=images/someimage.jpg everything works fantastic. Ok but what I am trying is use it to show thumbnails of a member on their profile page in which the img=images/someimage.jpg will change based on the member profile page you are on. What I tried was using a variables and sessions. In other words tried something like this imgsize.php?percent=25&img=”.$req_user_info['photo'].”. This seems to not pass to the imgsize script but when I view the source code of the page the correct image is showing but the script did not generate any thumbnail. Not sure if you can help out but I am not sure why the script does not generate a thumbnail from the variable. Any help of suggestions would be greatly appreciated. Like I said the script works great if the image is static but in my case the image changes based on the member. thank you again for a great script and for any help you might have.
Todd
I think it should work fine with variable images since I used it that way in one of my previous projects. Try this
imgsize.php?percent=25&img=< ?=$req_user_info[’photo’]?>
Mike
I copied the program just the way you posted it and i receive this error message on trying this:
http://localhost/imgsize.php?w=100&img=tmp/445e249e7fe39.jpg
Notice: Undefined index: percent in c:\archivos de programa\easyphp1-8\www\imgsize.php on line 29
Notice: Undefined index: constrain in c:\archivos de programa\easyphp1-8\www\imgsize.php on line 30
Notice: Undefined index: h in c:\archivos de programa\easyphp1-8\www\imgsize.php on line 32
hi im quite a newbie, how do i get this to work? like to show a page where you can browse for a folder then upload
Lucian, just add “error_reporting (0);” without the quotes before the line that says “header (“Content-type: image/jpeg”);” to suppress the notice messages.
rua, i’m quite confused of what you want to do. could you please explain?
Hi there,
This script looks perfect for what I wanted.
But can´t put it to work…
Instead of having the file as standalone, I´ve put it in an include and inside a function, but then it doesn’t work any more…
I think is because I have “echo” and other code before this script…
Is there a way to get it to work inside other code?
Thanks
Ok… I think I have done it…!!!
No more help needed…
Thanks for your script! It’s amazing
Hey man, amazing script! How can i resize a group of images(4)at once? a photographer goes to upload the imagens to my site, but if every day he have to resize and edit the quality of the images in photoshop….
Can you help me?
Sorry about the bad english man. brazilian.
Hi Alan,
Resizing a group of images at once would require some additional scripting. Idea is to create another script where you can pass multiple images as parameters – that script then will make the call to my image resize script for each image passed to it.
MIke
Fantastic work!
I had been trying to improve an image resize script to produce better image quality, but nothing seemed to work. I thought it was a limitation of the GD library, but your script proved my theory wrong. I can’t figure out what makes your script produce better images, but I love it.
May I ask how you learnt all of this stuff? I have been trying to teach myself from the net, but they tend to be either too simple or way out of my legue for now (the tutorials).
Thanks again,
Joe
I cannot get the script to work on my pages. I guess i’m getting the calling line wrong. This is what i’m doing.
> I’m loadig images dynamically using a name contained in the database. It gives me nothing.
What could i be doing wrong?
Jeff, pulling names from the database would be fine provided that the url you are passing to the script is correct.
Joe, I think what makes my script produce better image quality is the fact that I am handsome. Hehehe, just kidding. Actually, I think it’s the ImageCreateTrueColor function. Most examples would show the use of ImageCreate only.
As for where I’ve learned this stuff, well I guess it’s experience and my attitude of not stopping until I get a problem solved. I seldom use online tutorials personally and though most would say that I sometimes reinvent the wheel, I just love to do it.
Hi Mike, thanks for the reply. It seems the code i posted got flitered out. i have tried to use the image tag and just the plain usage’s you have provided but nothing seems to work. please give me a scenario on how to call the function on a page.
Hi Jeff, sorry for the code being filtered out.
To check for an error, try calling the script straight from your browser’s address bar instead of from within the img tag. This should show you any error message that might give you some clue.
Done that, gives me undefined variable like h, constraint and percentage then give me some gibrish – a jumble of numbers and letters mixed together.
Jeff, please paste here the URL that you placed in your browser’s address bar.
http://localhost/imgsize.php?w=150&img=../uploads/webmaster.jpg
Hi Jeff, the URL was truncated. Could you paste it here without the http part so that it doesn’t get truncated?
Hi I tried using this PHP script in a page I am creating. The way I used it was like so:
The pgoto didn’t show up… Am I using the script in the wrong way? If so, could you please tell me the propper way to use it? Thanks!
Hi Sam, how did you use the script?
I created a file called imgsize.php that file had this code in it http://www.mikelopez.info/download/imgsize.phps then in my actual page file (.php) i put i added spaces between the because last time i didn’t and the code didn’t show up. Any ideas why this didn’t work?
OK… ummm how do i post my code that i used? It keeps deleting it out of my comment…
Hi.
I’m a complete PHP noob so please be kind.
How can I combine this to an upload script? Everything Ive tried has failed… And when I run your script, it outputs the resized image perfectly, but does not save it? So if I open the original image its unchanged.
Thanks. Your help would be greatly appreciated!
Sam,
Just don’t include the greater than and less than signs.
Example: img src=”imgsize.php…”
Mike
OK the code i used was:
img src=”imgsize.php?percent=50&img=team_pictures/team001.jpg
and I had your imgsize.php file saved in the same directory as the PHP page file… Any ideas?
Hi Sam,
The way you used it seems correct. One possibility I have in mind is that the path to the image is not accessible. Could you try a full URL to the image? Say, http://somehost.com/team_pictures/team001.jpg instead of just team_pictures/team001.jpg?
Also, to view any possible error, try putting the image src to your browser’s address bar (i.e. http://somehost.com/imgsize.php?percent=50&img=team_pictures/team001.jpg and let’s see what errors you get.
Mike
What if I only want an image to be resized if it goes pass a certain width? Then I would want it to go down to let’s ay a width of 500px and the height would go down in proportion.
Jerry
Tomer, to save it you will have to open the URL via PHP. Here’s something you can do in PHP…
$img = implode (”, file (‘http://path-to-imgsize.php?..’));
$f = fopen (‘filename.jpg’, ‘w’);
fwrite ($f, $img);
fclose ($f);
Haven’t tested that code yet but I hope you get the idea.
Jerry, in that case you would have to edit the script to check for the image dimensions of the source image. The section that determines the dimensions of the source image is this:
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
Nice one,
Thanks very much for this really easy to use yet very effect script.
Brett
I used your script it is very nice Keep it up man
I have one problem in script I got image with resize with image is scrached it is not good visible After resizing can you help me to figure out it
thanks
Hi James!
What do you mean by scratched? What type of image are you trying to resize? JPEG or PNG? Try using it with a different image format and see if you still get the same problem.
Mike
hello, im php challenged, so my question is:
i have a site where my friends and family upload images, can this be implemented on that script?
Hi Phil,
This script is not meant for file uploads. Rather it’s meant to resize images that have already been uploaded to the server. But since you are php challenged as you said, that’s totally understandable.
To learn more about uploading files using PHP, please refer to the URL below:
http://www.php.net/features.file-upload
Mike
I’m still learning php and was wondering how could one make this into a automatic function that resizes an image into 3 different images?
Hi Joseph, one possible solution would be to create another function that would call the script three times – one for each size that you want and display them as well.
Mike,
Thanks for this script. I’m doing some database work for a local animal charity and I was having image distortion problems with my current one and this worked perfectly first time.
Mike,
Love the script. Thanks for making it real simple to use.
However I wanted to use it as a function and pass the variables to the function using
function imageresize($image, $width, $height, $percent)
being called by
imageresize(“pic.jpg”,50,50,0);
I’d like to change the image file name dynamically. The imageresize function is called within a html page but the output is garbled text. Any help appreciated.
Thanks Mike. I’ve figured it out
in HTML you use the tag like this…
Many thanks!
Hello Matt!
The HTML you typed was trimmed out by Wordpress. Could you retype it again and just replace the < and > with [ and ] respectively? Just for the sake of those others who will be reading the comments?
Thanks and glad to know that this simple script helped you and that you got it working the way you wanted it to.
Mike
Hi Mike, I think your script is exactly what im looking for but i have a problem! i have my upload page working ok but i cant figure out how to post to your script? I just dont know enought about PHP to do this, i tried using the header function but i was using it wrong!!!
hi martin…
you don’t post to the script. you just access it via http:// just like any other php page but with the parameters mentioned above.
mike
i am trying to use it in my website. but it does not allow me to use it with in HTML. it is showing some thing which is not understandable.
there was a problem with header but i delete this row.
it is working proprely if i do not use it with in HTML.
pls reply me as soon as posible.
Hi, Mike great script! Thanks.
If anyone one knows Matt from post 59 I wonder if you could contact him and have him repost his code snippet so we can read it. Thanks!
Firstly,
much respect to you Mike for this script! I am newbie to PHP. Ok heres where im at:
- ive uploaded my image to the server
- i want to now resize so im doing this at the moment:
echo “RESIZE!“;
it opens your page(imgsize.php) and shows me the resized image. But this does not change the saved one on the server.
Also, can i call your script without going to the page and staying there?
Thanks a lot Mike, really need this to work.
Shakeel.
@waqas
the only way to use this in HTML is to place the call in an img tag’s src attribute.
@shakeel
the script resizes the image dynamically and doesn’t touch the actual file on the server. it should be placed in an img tag’s src attribute <img src=”imgsize.php?…”>
if you want to save the resized file then you have to create another php script that captures the output of imgsize.php and save the output to another file yourself.
good work.
I AM A JUST A BEGINNER IN PHP…I DONT KNOW WHETHER I AM RITE OR WRONG ?
but if i am not passing the argument like w,h and it is giving some error.
so i modified like…
if (isset ($_GET['constrain']))
$constrain = $_GET['constrain'];
if ( isset ($_GET['w']))
$w = $_GET['w'];
else
$w = 0 ;
if (isset ($_GET ['h']))
$h = $_GET['h'];
else
$h = 0 ;
is it correct??
tnx — PHP Image Resize Script
Hi Mike, i’m trying to get the script to work, but as result it just gives me the url string writen in the browser window..
http://localhost/imgsize.php?percent=50&img=house.jpg
and doesn’t display the image..
Can you tell me what the problem is ?
Richard, try to include the complete path of house.jpg i.e.
http://localhost/imgsize.php?percent=50&img=/path/to/house.jpg
Mr Lopez:
Your image resizing script is well written. Nice work. I am however struggling to adapt your script to images stored IN a database.
Could you offer some advice how I might be able to do this?
Kind regards,
Jonathan
Tomer, Mike:
Just a note about writing to files instead of to the browser:
Mike says:
”
Tomer, to save it you will have to open the URL via PHP. Here’s something you can do in PHP…
$img = implode (â€, file (’http://path-to-imgsize.php?..’));
$f = fopen (’filename.jpg’, ‘w’);
fwrite ($f, $img);
fclose ($f);
”
Where in FACT if you look at the prototype for the ImageJPEG function:
bool imagejpeg ( resource $image [, string $filename [, int $quality]] )
you can write directly to the file from there.
try something like
@ImageJPEG ($thumb, “/path/to/wherever/filename.jpg”, 100);
Also Mike; ignore my question about the database thing.. ive sorted that out myself already.
good luck everyone!
http://www.php.net/imagejpeg
Hi Matt, and thanks for share your script!!
I think that its what i was searching for..
i want to set an automatic image resize during the uploads… is it posible with this script?¿ in that case… how i can insert it?¿
thanks on advance!!
Jonathan, thanks for the tip re writing to file… I wonder why I missed that. LOL.
Nico, yes it is possible but you will need to modify the script a little. I’ll leave that up to you.
Hi Mike,
Funny I also need to resize an image on upload, so I guess instead of an image url in the script I just need to pass the image to the script to process it and then place it in the images folder.. I am using a script to give each image an appended name equaling the user anme of the person uploading…, anyway I am getting there any pointer would be great !
Thanks,
Vincent…
Mike,
I can;t get it to work. I get the following errors:
Notice: Undefined index: percent in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\multidome\httpdocs\library\imgsize.php on line 30
Notice: Undefined index: constrain in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\multidome\httpdocs\library\imgsize.php on line 31
Warning: readfile(library/1.jpg) [function.readfile]: failed to open stream: No such file or directory in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\multidome\httpdocs\library\imgsize.php on line 83
Any ideas?
Realy nice script.
Fits my site realy well.
Thanks for great howto and great job with script.
Thanks
Jonny Larsson
Great script – thank you … now to be seen in action on http://www.fuzzbo.com! Many thanks.
THUMBNAILS THAT UPDATE AUTOMATICALLY AS A FOLDER CONTENT CHANGES!!!! WOW!!!! If you could combine your script with a small image rotator script I found it would be a match made in heaven for me… and many others who use Flash slide shows that autofeed from a folder using XML. The rotator script I found feeds random images (of various formats and any name) when the script is called…
ex: img src=”http://tacmusicintl.com/TEST/rotate.php”>
CHECK THE SCRIPT OUT HERE: http://www.hiveware.com/imagerotator.php
Your script combined with this would allow a RESIZED-RANDOM thumbnail to be selected from the full size images inside a slideshows folder. This is great because thumbnail can be hardcoded to open the index.htm(php,htm) file that iniates the slide show…
ex: a href=”javascript:void” onclick=”window.open(‘Slideshow.1/index.html’,”,’resizable=yes,scrollbars=yes,width=775,height=450′);”>
CHECK THE SCRIPT OUT HERE: http://www.hiveware.com/imagerotator.php
Here is a peek at that Rotator script I mentioned that would be GREAT coupled with your Resize script. Fresh thumbnail content to from image folder that auto-update.
0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = ‘Content-type: ‘.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists(‘imagecreate’) ) {
header (“Content-type: image/png”);
$im = @imagecreate (100, 100)
or die (“Cannot initialize new GD image stream”);
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, “IMAGE ERROR”, $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
Hi Mike,
Thank you – this looks like just what I need, but I have two problems.
1. I tried to create an account wit you, and my e-Mail address was refused – the one I entered here! I checked it three times – I do not know why it would be refused!
2. The real issue. I am working on a script that takes one huge uploaded file, rewrites it to three different folders – /images/thumbs, /images/webPage, /images/fullsize
Your code looks perfect for this – and let me thank you profusley for supplying it. You provided some code above for saving as files:
$img = implode (”, file (’http://path-to-imgsize.php?..’));
$f = fopen (’filename.jpg’, ‘w’);
fwrite ($f, $img);
fclose ($f);
Now, the charatcer inside the brackets of the implode function – just before ,file – what the heck is that? If I paste it into pico, it is a space, and acts like an illegal character. Text pad translates it as a pipe. I am familiar wit hthe implode and explode commands but cannot see what this should be. I also tried pasting from IE 7 and Firefox incase it was a Microsoft issue.
Thanking you in advance for any help you can give.
is it just two single quotes? That would make some sense. Let me try that – will post back if I get it going!
Thanks again! (it shows as only one char on my system – that char beinga double quote – is that the blog software trying to help?)
ok, that was two quotes – I had some issues with copy and paste – there were other illegal characters. Here is the ‘fixed’ code, with notes that need reading. Please note, I put no skill into this, the brains is from the original posters and coders, whom I thank thoroughly for their code:
Inside php tags:
$img = implode
(“”, file(“http://www.imydomain.com/myfo;der/imgsize.php?w=600&img=http://www.mydomain.com/files/filename.jpg”));
$fp= fopen(‘/usr/home/sites/www.mydomain.com/web/uploads/test.jpg’, ‘wb’);
fwrite ($fp, $img);
fclose ($fp);
Okay, if you get errors, copy the line in, typing it – this solved alot of my errors – especially on the fopen line. It is highly unlikley that your paths are the same as mine. If the path is wrong, you get an ugly error, that does not say what the problem is. Check the path twice if stiull erroring, copy the line in the implode tag at the start, starting wit hthe http ending with test.jpg (again on your system, it will be a different path and file name) If it doesn’t work, fix the path – when it works, copy it back into your php file.
To make this code do what you want may take some reffort – it is well worth it – this works quickly, elegantly, and accuratley, profucing high quality resized images..
I am very impressed!
Thank you to all who have contributed here – I am endebted
Hi Mike,
I’m using ur script but on the output i get …хЎ%(’©yґўZь»ђцЅ™{МҐу…
is the first line in the code so can u help me. I’m using the script in a WHILE loop, and want to resize several pics from image folder.
tx
Hi Mike,
I’m using ur script but on the output i get …хЎ%(’©yґўZь»ђцЅ™{МҐу…
header (”Content-type: image/png”) is the first line in the code so can u help me. I’m using the script in a WHILE loop, and want to resize several pics from image folder.
tx
Hi Mike,
this script is excellent. Results are fantastic. Thank you. I am desperately tryinng to figure out how to use this script to resize an image which is referenced by a row in a recordset. The image is not stored as a blob, but as a text link and the actual file lives in a folder on the server. My code as follows shows no images on my page. There is something I am missing in the img parameter but I cannot figure it out for the life of me.
Please help…
” ?>” />
Much appreciation to anyone who can solve this.
Cheers,
Teerock.
Perhaps I should try my code again.
” ?>” />
Well this is interesting… I’m going to leave off the opening ” ?>” />
“” ?>” />”
I give up on trying to post my code…
Hi teerok, try replacing the < and the > with [ and ]
kris,
the script is designed to work as a standalone script. it appears that you have placed my code inside your code.
mike
thanks for this cool script, i needed image resizing in an ajax gallery, and your script became a first-class helper for me!
works perfectly!
thanks
by the way, is there an option to edit the quality setting while re-encoding??
Hi SoulSmasher! To change quality of output, you can edit the script’s line that says:
@ImageJpeg ($thumb);
to something like
@ImageJpeg ($thumb, NULL, 75);
or something like that…
More info on ImageJpeg can be found at http://php.net/imagejpeg
Cheers!
Is it possible to adjust the JPEG compression level of the output image?
Great script, thank you!!
It seems like a common thread in these comments is the ability to use this to resize uploaded images. I had the same need myself so I thought I would share my code. I hope this helps someone.
//set the name and location where you want the file saved
$newFileName = ‘/path/to/save’;
//call your temp upload file via the image resize script
$handle = fopen(‘http://domain/path/imgsize.php?w=120&img=’.$_FILES['yourfileuploadID']['tmp_name'], “rb”);
//read the output of the script into a variable
$contents = stream_get_contents($handle);
//clean up file handle
fclose($handle);
//save optimized output to desired path
file_put_contents($newFileName, $contents);
//delete temp file created by upload
unlink($_FILES['yourfileuploadID']['tmp_name']);
A wonderful script! Saved me an hour of scripting.
I suspect a lot of the problems had by users are path errors to the php file and jpg file in how they write the link.
It was so simple to implement it – took a moment to realize you just put it in the src tag. I’m new to php (a few months) from ASP. What a difference! Things are so easy (and possible!) compared to asp.
I don’t know how to edit the code to make it only resize if width is greater than X pixels. Can you provide sample code?
Also it doesn’t work with animated gifs. It stops the animation and only displays a non animation version of the image.
Nile, please refer to my reply just above your comment
Joel Clermont, thanks for sharing your code
David, you’re welcome and nice to know I helped
Comment Blast, no it doesn’t work with animated GIFs. As for resizing only if width is greater than X, you have to edit the source code and add checking for the width. to do that, you can use PHPs getimagesize function. here’s the link – http://php.net/getimagesize
Is there any way for the file size to automatically change when an image size is changed (almost like a re-ize of crop function) in PHP, without distorting the image?
hi Randall,
You can output the resulting image to a file instead of to the browser… take a look at the imagejpeg function at http://www.php.net/imagejpeg
Note that the second parameter can be a filename. All you have to do is modify my source code to save to file instead.
Hope this helps.
MIke
I just downloaded this and think it’s wonderful. It’s just what I was looking for, however, I’m experiencing the black backgrounds with PNG and GIF images. You mentioned you knew how to fix it, but didn’t have the time. Could you explain what I need to do to fix the black backgrounds? Thanks.
Hi folks, hi Mike.
I did some time ago an “imager.aspx” ASP.NET script which was almost identical in features (width, height, portrait/landscape handling etc.); I was looking to port it in PHP (newbie in this language for now…), when I found your very precious script.
I just wrote a modified version of your script, including another parameter that my .NET script used to handle, i.e. a “q” to specify a quality if present, or output at default quality if *omitted*.
I think it can be useful for a web programmer, as it makes able to fine-tune the data load when, f.ex., generating a wide list of thumbnails.
So, I read some posts about image quality… insert / modify these lines (changes are marked with // NEW):
…
$w = $_GET['w'];
$h = $_GET['h'];
$q = $_GET['q']; // NEW
…
[CUT]
…
// Output resized image
if (isset($q) AND $q>=0 AND $q
Maybe my post got cut… last lines are:
if (isset($q) AND $q>=0 AND $q
Sorry, can’t seem able to post the code, maybe because of some quirks in the blog engine
I’m trying to insert via HTMLentities, feel free to edit my post and sorry for being the third one
if (isset($q) AND $q>=0 AND $q<=100) @ImageJPEG ($thumb,”",$q);
else @ImageJPEG ($thumb);
Not sure if anyone will find this useful, but I have found the solution to the black backgrounds on transparent gifs and pngs. I have updated this script as well as added a few other features, such as other image formats, support for animated gifs (when smaller than requested thumbnail), no-resize on smaller images (smaller than requested dimension), as well as a full size image viewer.
http://blog.briandichiara.com/image-thumbnail-creator/
Thanks Mike for this and I hope my additions are helpful to others.
Hey, I tried using an absolute path on my server (http://domain.com/folder/something.jpg) as the location of the image, and it just echo’s the URL of the image resizer. How do I make it work with the absolute image path? It works fine with a regular path.
Thanks a lot.
First off thanks mike for an awesome script. I’m using it in a new site I’m developing and it is working wonders. I originally had modified the script to pull images from a database, but have since decided to store the file location rather than image data, and reverted to the original script.
However, if any one needs to get images from a database, here’s a link for the modified script.
http://salcodrip.com/~danno/scripts/img.php.html
I love your script, saved me alot of time! ! !
I’m using simply special software for photo resize.
@John… the point of this script is to dynamically resize images on the web so the software you’re using is most likely beside the point.
Very nice script!
The only problem I found is that it doesn’t show pictures with spaces (or %20) in the file name. Is there a solution for this issue?
Hi, sorry haven’t had time to look at the code but perhaps a call to urldecode would fix it?
Unfortunately, urldecode($_GET['img']) doesn’t do anything…
Mike, Love the script and your easy directions!! Thanks! I have one problem though
When I use your string…
Print ” “;
This is the result I get… (and the image does not show up)
http://www.domain.net/imgsize.phps?h=75&img=http://www.watchzone.com/watchzone/images/es1006.jpg
Can you show me a way to make this work?
Thanks for the script and your time!!!
Randy,
You have to rename it to imgsize.php and not imgsize.phps
Mike
Hi Mike…
Excellent job buddy. Thanx for your simplified script. I have an issue Mike. I am a beginner, so i am not sure about coding. I think, the script which you posted is for resizing an already existing image. But, what i want is to upload a new image and then resize it. I want both the uploaded and resized images to be saved…
Hoping a quick reply from you. Please, help the needy.
Thanx a tonn in advance…
Ramz
Hi Ramz,
I could give you the entire code but that would take the fun away…
For saving the uploaded image… use the function move_uploaded_file
http://php.net/move_uploaded_file
As for saving the resized image… you can use use the same script as i have here but change the last function in the script (ImageJpeg) to include the filename as the second parameter.
http://php.net/imagejpeg
If you have more questions to clarify, feel free to ask.
Mike
Hi, I’m sure that this is a very basic question for most people viewing but here goes!
I’ve used PHP to create an image upload form that inserts the filename into a database and the image file into a folder. This works fine. My question is, can I get PHP to resize an image as it is being uploaded without GD intalled?
Many thanks
Hi Dave,
There’s one more way to do it provided that you have Imagemagick installed on your server. You can use PHP’s built-in exec command to call imagemagick’s “convert” program to do the resizing for you.
I think most servers have imagemagick installed so all you have to do is test if the program exists.
Mike
hey Mike, Thanx for d reply,
I am posting my code here:
height new: $new_height”;
echo ‘
‘;
?>
When i upload a image, i get an error as a small square box and the images and thumbs are not stored in their destination folders.
Please help me out…
Thanx,
Ramz
height new: $new_height”;
echo ‘
‘;
?>
Hi Mike,
Thanks for getting back. I’ve run phpinfo() and can’t find any mention of Imagemagick so I assume it isn’t installed. From the research I’ve done it seems the hosting package I have isn’t very good as there is no GD/Imagemagick installed. I guess It’ll be simplest to switch packages!
Again, many thanks, I’m only a couple of weeks into teaching myself PHP and all help is much appreciated!
Dave
Mike,
I’m trying to use Joel Clermont’s codes to resize the image as I upload via your imgsize.php code, but I get “Call to undefined function: stream_get_contents() ” error. Could you tell me how to fix this problem?
Following is what I have now. Any advice will be helpful. Thank you.
//set the name and location where you want the file saved
$newFileName = ‘upload/test.jpg’;
//call your temp upload file via the image resize script
$handle = fopen(‘http://saitopia.com/template/display/imgsize.php?w=120&img=’.$_FILES['uploaded']['tmp_name'], ‘rb’);
//read the output of the script into a variable
$contents = stream_get_contents($handle);
//clean up file handle
fclose($handle);
//save optimized output to desired path
file_put_contents($newFileName, $contents);
//delete temp file created by upload
unlink($_FILES['uploaded’']['tmp_name']);
Hi Kate,
stream_get_contents only works in PHP5
try using file_get_contents instead.
Mike
Hi there,
first of all – great script! really liked it..and i keep using it on all of my sites!
i have a question, i have a watermark script which i refer to as wimage.php?IMAGE.JPG and it adds a PNG based watermark protection.
now, when i refer imgresize.php?w=100&h=100&img=http://www.FULL-URL.com/wimage.php?SomePhoto.jpg it works great, i mean, its a full combination of 2 scripts, first it puts watermark and then it resizes it. the problem is that it takes too long because of the re-calling for the images. i am trying to access now imgresize.php?w=100&h=100&img=images/photos/SOMEPHOTO.jpg it gives me an error. how can i combine these two scripts? or how can i simply add a watermark protection (PNG based) to this awsome script???
Hi Lior,
You can actually edit my script to include watermarking into it. Just view the code of your watermarking script and copy whatever section of it does the watermarking. I of course assume that you know some PHP.
Mike
Mike,
After LOADS of searching, I think I may have just found what I’m looking for. I have a custom image uploading script on my site that I need to add image resizing to. I believe that I can incorporate your script to meet my needs. However, as I am not a PHP guy by trade, I’m not sure I can go it alone. Do you do contract work like this? If so, please let me know.
Peace,
Rick
Thanks for sharing! Saved me several hours of work and pounding angrily on my keyboard.
Love the script! It took me some finagling to get it working but now I’ve got it working to set dynamic background images in divs.
Thanks
Hello and thanks for the great script! It works just fine and does what I was looking for.
My question is the following…
If the picture URL is under the following extention “.ashx” (example: ./mypicture.ashx?aCode=rc111), it does not work.
How can I get around this problem?
Keep up the great work!
I have not been able to get this script working as other have and I cannot figure out why….
An example link is: http://illuminated-design.com/newzealand/imgsize.php?w=50&h=100&constrain=1&img=/images/photos/IMG_0827.JPG
All I end up getting is a small box with a red X through the middle. Any ideas?
I figured it our. Some of the images were just too large to work with, I’m assuming as a result of the max memory allocated to me by my host. Same problem I have run into in the past as I am trying to compress very large images. Guess I’ll just have to shrink them in photoshop.
Time consuming…..
Hey Mike, I want to use your script to resize some images that are being submitted through a form by my users. It looks like your script may do the job, but one question. My existing php script emails the test responses and the pictures as an attachment(s). How do I integrate your script to resize the images, and then email them to me?
Need a little direction….
Nice simple script, thanks.
I had some problems with it not displaying the image. It was bugging me for ages as I’d double checked everything.
Turns out that because of a lack of some of the peramiters (for example if you’re just using w=50 and letting the script do the rest) my PHP was giving an error in the imgsize.php file.
If anyone else is having this problem, just try adding
error_reporting(0);
at the top of the imgsize.php script. It did the trick for me!
Hi Mike,
Two questions,
1) Some other authors in their solution call after the creation of the final image the following lines :
ImageJpeg($thumb, null, -1);
ImageDestroy($img);
ImageDestroy($thumb);
2) What is the difference between calling:
ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
ImageCopyResized($dst, $src, 0, 0, 0, 0,$tn_width,$tn_height,$width,$height);
Many thanks for your comments, and by the way your script is great !!!
hey mike,
i’d like to get support for the other formats, how exactly do you compile the GD library to support gif?
Thanks
kristian
Hi Kristian,
GIF support should already be enabled by default. As for compiling GD you might want to check the GD site for that – http://www.boutell.com/gd/
Mike
Hi Mike, ive been clicking search engines entire day, im familiariced with resize images, i have a site http://www.tecnovideosar.com which produce thumbnails and stuff. But i come accross with a very larger proyect, so its necesary to have images stored in database, again, no problem, i can upload them there, extract them and everything, BUT, i CANNOT find a way to resize this database images, cuz the GD commads can only read FileNames, not sources or stuff, PLEAS HELP!! =(
Srry for duoble post, i DONT want to store the 2 or 3 versions of images in database like lots of pages suggest, i want to have 1 version uploaded, then open it, then resize it, tanks, you are my only hope lol
Hi Victor,
Here’s how I would do it…
1. Save the image from the database to a file
2. Resize the file
That should work.
Also, I would recommend that you change the system to put images in files instead of in a database. This will dramatically reduce database load.
I thougth about having a tmp file to resize, but its a site that will show for example 30 products thumbnails each page, and lots of simultanious users will visit it, so cpu load its a waste, about database load, it doesnt matter the Mb it is, but the charge in querys or math you give to it, retrieving info is not big deal, and storing in database have lot of advantages like easy to reply trough servers or to backup. However i think theres no way out of this, cuz the GD library seems to work only with files, i hope theres an update in the future, cuz, sometimes is not posible to have everything on directories, for example free pic galleries for 5000 users, which every user have at least like 20 – 40 pics, imagine that. its harder to secure images in directories than in DB which will require session and maybe a numeric key to retrieve it. How ever thank you very much, i saw your code, and its much cleaner than the one i had in my site, ill use it, thanks alot!
Hi Victor,
I didn’t know that you had security requirements and the traffic you’re having. I’m thinking of another solution, my script also accepts an image URL instead of path to a file. Why not do this:
1. Write a script that will display the image from the database. I believe you already have this.
2. Use my script to resize the image based on the URL of actual image.
What do you think?
Mike
thank you for the script.
your script very usefull.
Thought I would offer this as several posts here seem to suggest a lack of understanding in using the script.
Step #1 Upload the script to your server or webspace. I had to change the the script to .php from it’s original .phps
Step #2 Reference the script in any html document as many times as needed just like you would a regular call to an image in the html document. Brackets are removed below so you can see the code.
img src=”http://www.sitecompany.com/imgsize.php?percent=50&img=Banner.jpg”
You can call as many images as you need this way on a single page by simply calling the images THROUGH the script via modified image tags in your HTML document.
For my use nothing was required other than that. The source files I am calling are in the same directory as the the script, but could easily be somewhere else such images/Banner.jpg.
For testing purpose you could even reference the image I used above on your own page to try different perecentage or height width perameters.
It’s very easy to use. Thank you very much Mike!
The only problem I had which I believe another comment touched on was that it does not seem to work with images of a certain size. The images that failed for me were around 700k in size. I have yet to test to see what the actually failure threshold is. All images of 100k or less worked fine.
I am checking with the company that manages my servers to see if their is some setting not related to the script that is preventing files of certain sizes from being processed by the script.
I will report back my findings and any solutions.
Hi Brian!
Thanks for the quick “tutorial”
I should have done it myself… hehehe.
Also, please let us know what your findings are regarding the problem with image sizes.
Mike
Will do. My little tech army is looking into in now. Should have solution soon.
We had some progress at solving this but still no answers on why it was occuring. We did determine WHERE it was occurring.
The solution is to make sure niether the imgsize.php file nor the source files are in the root directory. They must be in a subdirectory of the main site. Example: http://www.mydomain.com/images/imgsize.php and not http:www.mydomain.com/imgsize.php
It is not necessary for imgsize.php and the source file to reside in the same directory but testing our testing suggested that for large files both must be in a subdirectory beneath the root or www directory.
I was able to get files of any size (1.7 megs was the largest) to resize perfectly only when both the imgsize.php file and the source files where within a subdirectory of the site.
I have yet to determine what the threshold is for the files not working properly from within the root directory but it seems to work flawlessly on any file so long as both are not in the root.
Hi Brian,
That’s interesting. Like you though, I can’t reconcile why this is so. At least for now, we have a solution that will make this work for large images. Thanks a lot!
Mike
I encountered a similar problem with another script. This time we discovered what the true source of of the trouble was so I am back to offer my findings.
The problem was in the php.ini file. The php.ini was set to only commit small amount of memory to the process. Mine was set to 8m which seemed to be more than enough memory to handle images of around a meg; however, it clearly wasn’t.
I incrementally started increasing the the value higher until I was able to process files of 5megs or more. The value I had to set mine to was 128m. I am still a little baffled on why so much memory is required but it solved the problem so I am moving on.
Here is how you can fix this yourself.
1. Open your php.ini file.
2. Find the line that reads memory_limit = 8M (it might say 16m or some other value)
3. Increase it to whatever value lets you process the images without error.
The reason this was a problem for some and not other is based on two elements.
1. The images being processed may have not been very large and therefore didn’t break through any sort of threshold that prevented them from beings processed.
2. The php.ini could contain any value set by the host. The default values set on my servers are 8m. Other host may set them higher by default.
Note some hosts may not read in the php.ini file so changes you make might have no impact. Check with your hosting if you increase the memory_limit to some insanely high number and you are still getting errors. They also might impose a secondary limit on the amount of memory committed to any process on any one domain
so you don’t unduely overburden the server and thereby impact other sites colocated on the machine.
Is there any way to extend this to “crop” x amount of pixels? Currently, it “resizes” the image, which makes some of them look really crappy.
You don’t have to host CPU-intensive image resize scripts on your server anymore.
There already exist services for remote, on-demand image manipulation.
SteadyOffload (http://steadyoffload.com/thumbnail-problem) can do basic image processing (resizing, cropping, flipping, etc.) remotely. You simply use a custom HTML attribute with the IMG tag and the resulting thumbnail is delivered from their cache servers:
<img srcx=”image.jpg” xmanip=”RescaleWidth 120″ xjpegquality=”70″ />
Much, much easier than all the hassle with GD, ImageMagick or whatever else.
Hi Jim,
Nice service there Jim. I signed up for an account and I find it pretty cheap. About $5 for 1GB of bandwidth. Not bad. I wish you had the price posted on the sign-up page. I found the price only after signing-up.
On the other hand, there are people who still wouldn’t be willing to pay for an image resizing service.
Mike
exalent code…………………………………….
thanks brother……………………
i am from india………………………………………..
Hi i’m writting an Auto Gallery PHP script and this is a perfect thumbnail addon. However, all images in my gallery are jpg, yet only some are displaying. I checked things like spaces and symbols in the names but they are all pretty much the same…
I just get blank spaces on some of the image placeholders. I checked the dirs and it’s all correct, hey just won’t display…
Any ideas?
Hi Jake,
I’m not really sure as to what the real cause of your problem is but my hunch is that your server settings is blocking repetitive access to the same PHP script within a short time span. I’m not sure as to what you need to do with your web server though.
I suggest that you lessen the number of images displayed by the script per page.
Mike
Hi Mike,
great script, but unfortunately I’m trying to use it, but the only result that’s givng me is…nothing!
I’m using the script off-line, with EasyPHP 1.7 installed, and the result I get is
http://localhost/icoltelliditore/imgsize.php?w=600&img=images/1.jpg
why?
GD Library are correctly installed…so?
Please help me…thanks a lot!
Gigi
Hi, this script is great, but highly intensive. Is there anyway to improve that and/or implement some sort of caching? Thanks.
this is great… more power…..
I have made a little work around as I wasn’t too happy with the quality of GIF images when converted to JPEG format by the script.
I replaced,
// Output resized image
@ImageJPEG ($thumb);
with the following,
// Output resized image
$type=getimagesize($img);
$type=$type[2];
switch($type){
case “1″:
@ImageGIF ($thumb);
break;
case “2″:
@ImageJPEG ($thumb);
break;
case “3″:
@ImagePNG ($thumb);
break;
}
This is a fantastic script! Thanks for publishing it.
Ed
hi.. im not really good at php..
im just wondering if your script can support the uploaded picture for resizing?
i mean, i have this project that when you uploaded a picture it must be resized for a specific height and width.. thank you very much..
Hi Yas,
You will need to edit the script a bit so that it saves the output to a file instead of just sending it out to the browser for display.
Mike
Very nice Thanks for sharing this will help alot….
#
first of all – great script! really liked it..and i keep using it on all of my sites!
i have a question, i have a watermark script which i refer to as wimage.php?IMAGE.JPG and it adds a PNG based watermark protection.
now, when i refer imgresize.php?w=100&h=100&img=http://www.FULL-URL.com/wimage.php?SomePhoto.jpg it works great, i mean, its a full combination of 2 scripts, first it puts watermark and then it resizes it. the problem is that it takes too long because of the re-calling for the images. i am trying to access now imgresize.php?w=100&h=100&img=images/photos/SOMEPHOTO.jpg it gives me an error. how can i combine these two scripts? or how can i simply add a watermark protection (PNG based) to this awsome script???
Hi Nice script
Here is an addon by Torstein Hønsi for creating sharper thumbnails. Simply paste this function at the bottom of the existing script and call it just before the last line of the existing script like so..
You can change the parameters as you like.
Sean
///////////////////////////////////////////////////////////////////////////
$thumb=UnsharpMask($thumb, 100, 0.8, 2);
@ImageJPEG ($thumb);
//////////////////////////////////////////////////////////////////////////
function UnsharpMask($img, $amount, $radius, $threshold) {
////////////////////////////////////////////////////////////////////////////////////////////////
////
//// Unsharp Mask for PHP – version 2.1.1
////
//// Unsharp mask algorithm by Torstein Hønsi 2003-07.
//// thoensi_at_netcom_dot_no.
//// Please leave this notice.
////
///////////////////////////////////////////////////////////////////////////////////////////////
// $img is an image that is already created within php using
// imgcreatetruecolor. No url! $img must be a truecolor image.
// Attempt to calibrate the parameters to Photoshop:
if ($amount > 500) $amount = 500;
$amount = $amount * 0.016;
if ($radius > 50) $radius = 50;
$radius = $radius * 2;
if ($threshold > 255) $threshold = 255;
$radius = abs(round($radius)); // Only integers make sense.
if ($radius == 0) {
return $img; imagedestroy($img); break; }
$w = imagesx($img); $h = imagesy($img);
$imgCanvas = imagecreatetruecolor($w, $h);
$imgBlur = imagecreatetruecolor($w, $h);
// Gaussian blur matrix:
//
// 1 2 1
// 2 4 2
// 1 2 1
//
//////////////////////////////////////////////////
if (function_exists(‘imageconvolution’)) { // PHP >= 5.1
$matrix = array(
array( 1, 2, 1 ),
array( 2, 4, 2 ),
array( 1, 2, 1 )
);
imagecopy ($imgBlur, $img, 0, 0, 0, 0, $w, $h);
imageconvolution($imgBlur, $matrix, 16, 0);
}
else {
// Move copies of the image around one pixel at the time and merge them with weight
& 0xFF);
// according to the matrix. The same matrix is simply repeated for higher radii.
for ($i = 0; $i 0){
// Calculate the difference between the blurred pixels and the original
// and set the pixels
for ($x = 0; $x < $w-1; $x++) { // each row
for ($y = 0; $y > 16) & 0xFF);
$gOrig = (($rgbOrig >>
$bOrig = ($rgbOrig & 0xFF);
$rgbBlur = ImageColorAt($imgBlur, $x, $y);
$rBlur = (($rgbBlur >> 16) & 0xFF);
& 0xFF);
$gBlur = (($rgbBlur >>
$bBlur = ($rgbBlur & 0xFF);
// When the masked pixels differ less from the original
// than the threshold specifies, they are set to their original value.
$rNew = (abs($rOrig – $rBlur) >= $threshold)
? max(0, min(255, ($amount * ($rOrig – $rBlur)) + $rOrig))
: $rOrig;
$gNew = (abs($gOrig – $gBlur) >= $threshold)
? max(0, min(255, ($amount * ($gOrig – $gBlur)) + $gOrig))
: $gOrig;
$bNew = (abs($bOrig – $bBlur) >= $threshold)
? max(0, min(255, ($amount * ($bOrig – $bBlur)) + $bOrig))
: $bOrig;
if (($rOrig != $rNew) || ($gOrig != $gNew) || ($bOrig != $bNew)) {
& 0xFF);
$pixCol = ImageColorAllocate($img, $rNew, $gNew, $bNew);
ImageSetPixel($img, $x, $y, $pixCol);
}
}
}
}
else{
for ($x = 0; $x < $w; $x++) { // each row
for ($y = 0; $y > 16) & 0xFF);
$gOrig = (($rgbOrig >>
$bOrig = ($rgbOrig & 0xFF);
$rgbBlur = ImageColorAt($imgBlur, $x, $y);
$rBlur = (($rgbBlur >> 16) & 0xFF);
& 0xFF);
$gBlur = (($rgbBlur >>
$bBlur = ($rgbBlur & 0xFF);
$rNew = ($amount * ($rOrig – $rBlur)) + $rOrig;
if($rNew>255){$rNew=255;}
elseif($rNew255){$gNew=255;}
elseif($gNew255){$bNew=255;}
elseif($bNew<0){$bNew=0;}
$rgbNew = ($rNew << 16) + ($gNew <<8) + $bNew;
ImageSetPixel($img, $x, $y, $rgbNew);
}
}
}
imagedestroy($imgCanvas);
imagedestroy($imgBlur);
return $img;
}
Thanks for such a good code…
for those who have problem specifying a max width, I made this change. In my case, I only care about the width of picture.
If the picture width is greater than my the width I supplied, then the picture width will be set to the suplied value and the height will be scaled relatively to the with.
If the with is less than the supplied value, I leave the sizes alone.
Replace this:
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
by this:
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else{
if (isset ($w) AND !isset ($h)) {
if ($sw > $w){
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
}else{
$w = $sw;
$h = $sh;
}
} elseif (isset ($h) AND !isset ($w)){
Thanks for that – a good script! I’m trying it out now on a new site.
Thanks.Great !
Thanks a lot Mike!
Made a small change for resizing images for mobile phones:
1) Added 2 querystring parameters mh (mobile height), mw(mobile width)
(screen resolution of the handset to be passed in mh,mw)
2) Add the following code:
$maxWidth=$_GET["mw"];
$maxHeight=$_GET["mh"];
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
If ($maxWidth > 0){
$maxWidth = ($maxWidth * $percent) / 100;
$maxHeight = ($maxHeight * $percent) / 100;
If ($sw > $maxWidth || $sh > $maxHeight) {
$deltaWidth = $sw – $maxWidth;
$deltaHeight = $sh – $maxHeight;
$ScaleFactor=0;
if ($deltaHeight > $deltaWidth){
//Scale by the height
$ScaleFactor = $maxHeight / $sh;
}else{
//Scale by the Width
$ScaleFactor = $maxWidth / $sw;
}
$w = $sw * $ScaleFactor;
$h = $sh * $ScaleFactor;
$percent=0;
}
}
Mike’s code….
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;…….Mike’s code continues……
PS: percent parameter is must in this script. The code accepts height and width of the handset screen and then resizes it on the basis of percentage mentioned.
eg:
thanks,
Retesh…
I’m new to php so was looking how to do this. Very usefull but I think the code is in the wrong order. Your making assumptions the input is going to be an image, ok you have it dump an error message if it’s not valid but user’s don’t want to see that, much better to just output a default image ( in the if (!$im) { section). If you do img=index.php you get warnings because your trying to do calculations on non existant image dimensions without first checking it’s actually an image. I moved the whole image resize bit to the bottom else statement and shouldn’t there be a imagedestroy($thumb); at the bottom too? It pointed me in the right direction so thanks for posting it.
am an amateur in PHP. I used ur script to get desired result in localhost, but when I uploaded to server, am getting blank page !!! am I doing anything wrong?
phpnewbie: imagedestroy is not really needed in this case.
Jk: make sure that your server has GD installed and that php is compiled with the gd library. You can check this by uploading a php file containg the phpinfo() function.
Mike
Mike, here u go –
gd
GD Support enabled
GD Version bundled (2.0.28 compatible)
FreeType Support enabled
FreeType Linkage with freetype
GIF Read Support enabled
GIF Create Support enabled
JPG Support enabled
PNG Support enabled
WBMP Support enabled
XBM Support enabled
If u see the link, When I changed parameter from width= to w= and from height= to h=, I can see the image, But not the resized one !!!
Thank you for sharing this script. it really helps to re size the image using code.
Hi Mike, do you have an answer for the Que above, ‘Coz I am unable to resize it on a server…
Thanks for this! I have tested it adding just one image for now, but this is perfect for an image gallery I will be designing for a school site. I made one of the teachers bigger and smaller over and over and worked just great
WoW! This is AWESOME! I cannot believe somebody FINALLY did it. I don’t get to code as much, so, I am still kinda a newbie to PhP, kinda not really, but this is SUCH a T I M E S A V E R!!!!!!! I want to say thank you big time. You just saved me four or more hours of trying to figure out how to get it done correctly, with the constraint variable. ANyone can just use , but constraint is hard to define, at least for me. Thanks again. I am excited.
Mike, thank you for this script. I was having trouble on my site using my previous resize script and I replaced it with this script with no problems. Really very happy that you made this available. Thanks.
I just can’t get it to work. I end up with a square with a red cross in the middle. I uploaded the file imgsize.php and an appropiate image to the same folder. I created a file resizer.php and try to trigger your script with the following lines of code
<body>
<?php
echo ‘<img src=”http://www.mypage.com/art/imgsize.php?percent=50&img=ccx.jpg”/>’;
?>
</body>
GD is installed en enabled on the server.
try passing the full url of the image to the script.
Hi Mike,
This is a very cool script!
I want to ask you something. can I add some features to this script and post it to my site? thanks before.
Sure Nash! I’ll be definitely glad if you can link back to this site though.
Hi Guys,
I’ve added some features to this script:
* Displays a default image if the requested image doesn’t exist.
* Hide the image path
Check it out!
http://nashruddin.com/PHP_Image_Resize_Made_Easy
special thanks to Mike.
Great work Nash!
Hi Mike,
Great script…thanks for making it available!
One thing I’m having trouble with is sometimes the image won’t display at all when using the script and I’ve no idea why.
For example, this image doesn’t render:
http://petermcphee.com/img.php?w=100&img=test.jpg
But a 2nd jpg:
http://petermcphee.com/img.php?w=50&img=sarah.jpg
does work. If you take away the script component you will see that the images are valid but for some reason the first doesn’t load with the script.
Any ideas? Thanks Mike.
Hi Peter,
No idea. My guess is that it could have something to do with the image. Could you try re-saving the image and see if it works?
Mike
Mmm, weird. Must be corrupted some how. I resaved to another jpg and gif and still doesn’t work. No worries though, it works all the other times. Thanks anyway!
This is awesome! Thanks alot
hi mike
i would like to ask that this script will reduce the size of image also.
i means if it reduces the height and width then it will also reduce the size in kbs.
mean if a 1mb pic is 500×500 pixels and we reduce the size to 100×100 then will it reduce the size of pic from 1mb to 500kb
jas
Actually, it will reduce the size as well.
hi mike
thanks for reply. so i implement your code but not able to display image.
This is the implement code
echo “” .”" . “”;
This is the original code
echo “” .”" . “”;
what path am i giving wrong
jas
hi jas
how can i write php code in the comment box to ask the problem what m i facing
vineet
My hosting company just migrated me over from a PHP4 server to PHP5; the script worked great before but since the switch no images appear at all when using the script.
Are there any known issues with PHP5?
Server has GD installed but not ImageMagick; could this be the problem?
i tested it in php5 and it works just fine. you have to be sure that GD is also enabled in PHP
I have used, but in some gif and jpg images, it becomes black background.. Otherwise it is nice..
Thanks
http://www.colorart.in
Dear
i m using ur script but when calling ur script like this
<a href=’3gp-details.php?id=$id’ rel=”nofollow”>$name</a>
“;
, i m getting this error message :
Parse error: syntax error, unexpected T_STRING in /home/wallpap1/public_html/freaky/index-testing2.php on line 188
my images are in /public_html/freaky/resizer/images/big/
and ur script file is in
/public_html/freaky
please help how to use ur script.
Hi salman,
Are you sure you’re using my script? I’m asking because my script is not named as you specified.
mike
Hi Mike,
thanks for this script, working great so far!
I couldn’t find a way to pass the resized image dimensions to the html img tag so that page rendering is a bit quicker – like so:
imgsize.php?w=50&img=path/to/image.jpg width=”newwidth” height=”newheight”
Is there a way to do that? How do others get along with page rendering?
Alexandra
Hi!
When I try to display images captured with my digital camera nothing att all shows but when I resave the file in PS from 300dpi to 72dpi it works just fine. Is this something that could be solved?
Thanks!
I added a functionality to avoid images which dimensions are smaller than the specified dimensions not to be enlarged, with the parameter ‘max’ set to 1
$max = $_GET['max'];
if (isset($max)) {
if ($sw < $w) {
$w = $sw;
}
if ($sh < $h) {
$h = $sh;
}
}
an example:
imgsize.php?img=hello.jpg&w=50&h=100&constraint=1&max=1
This will resize to 50 pixels width OR 100 pixels tall, whichever resulting image is smaller, but if the image is smaller than 50×100, then i will not be resized.
Thanks for this little class, I’ve used it on a few times and it’s saved my butt!
Thanks you too much, this is working very good! You are perfect guys.
Using this script one can open any image on the target server as long as they know the path of the image, even in system folders eg
http://www.example.com/imgsize.php?img=c:\windows\Greenstone.bmp
Is there a way to restrict this script’s access to those folders only accessible by web user and not across the whole server?
Hey I like this script! I have incorporated it into an image gallery from a recordset. Can I just ask a question? Is this reducing the file size (kb) or just the size in pixels?
It reduces the file size too.
[13-Apr-2009 16:24:35] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 58
[13-Apr-2009 16:24:35] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 61
[13-Apr-2009 16:24:35] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 65
[13-Apr-2009 16:24:35] PHP Warning: readfile(images/im02.jpg) [function.readfile]:
failed to open stream: No such file or directory in /home/mysite/public_html/baby/include/imgsize.php on line 82
[13-Apr-2009 16:25:40] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 58
[13-Apr-2009 16:25:40] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 61
[13-Apr-2009 16:25:40] PHP Warning: Division by zero in /home/mysite/public_html/baby/include/imgsize.php on line 65
[13-Apr-2009 16:25:40] PHP Warning: readfile(images/im02.jpg) [function.readfile]:
failed to open stream: No such file or directory in /home/cadizhyp/public_html/baby/include/imgsize.php on line 82
now i have checked everything and i cant seem to figure out why im getting this, its only with certain jpg’s this happens with, is there a size limit for the images that can be resized?
If you are displaying multiple thumbnails on the same page and you notice some load, then others don’t and after a while you get the dreaded 403 forbidden error by Apache, maybe you have the MOD_EVASIVE security module installed:
To fix this, if you have access you should have to open your mod_evasive.conf file, usually located in the /etc/httpd/conf directory. The following configuration did the trick for me:
DOSHashTableSize 3097
DOSPageCount 5
DOSSiteCount 100
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 2
I was researching this for two days, so I hope it helps other people, because the error is very difficult to diagnose.
Greetings from the Dominican Republic,
Luis Pichardo
http://www.solusistemas.com
This was such a helpful script. I usually code in ColdFusion, but the site that I’m currently working on is on a server that can only run PHP, so I’m having to wing it. I needed to do some dynamic image resizing in PHP and a google search turned up this page.Even though I’m not fluent in PHP this script was easy to use, did exactly what I needed it to do, and even pages with a lot of images to resize load very quickly. Thanks so much for sharing this script!
-Delaney
im having another problem i was hoping someone would help me with.. here is what i got going on:
but it is not displaying anything.. help?
Hey , author of the script your script it’s super but , change it please.
I’m finding 2 hours error, but error is very simple:
add on the top of the script this code:
ini_set(‘display_errors’,0);
somehow, this doesnt work in my site http://mobitube.wapodium.net I resize the thumbnail image to be larger but when i check the image info, original dimension 60px x 45px and i try to resize it to 82px x 61px
it says 82px x 61px (scaled to 60px x 45px) supposedly, it shows the other way around. 60px x 45px (scaled to 82px x 61px)
Mike, I am trying to combine the script with another called images.php that pulls the image from a mysql database. There are a couple of references to doing this in the comments above. One writer says it works fine but is slow i.e. put images.php?id=99 (or whaterver the id number of the image is) where the path and jpg variable should be. I tried this but the images.php file does not execute and I get a broken link where the image should be on my web page. I tried replacing images.php?id=99 with a variable that includes the full path including domain name i.e. $image_file = “http://www.mydomain.com/images.php?id=99 and then inserting the $image_file where the path to the .jpg file should be in your script. This does not work either.
There is a reference above to a modified script on making this work , but the link is broken. ( as quoted below) Any suggestions appreciated! Here is the quote with original link. If anyone has the script from this link, could they post it please?
” First off thanks mike for an awesome script. I’m using it in a new site I’m developing and it is working wonders. I originally had modified the script to pull images from a database, but have since decided to store the file location rather than image data, and reverted to the original script.
However, if any one needs to get images from a database, here’s a link for the modified script.
http://salcodrip.com/~danno/scripts/img.php.html“
Hi Andrew,
Just off the top of my head, when you create the image through images.php, do you output the correct image headers such as:
header(“Content-type: image/jpeg”);
Mike
i know there are refrences above on using this script for remote images using a url. I would like to point out that i CANNOT get ANY remote images to load also would like to note that some images even local will not show. any ideas on this?
I implemented your script but my images that resize are blurry? Not sure what I’m doing wrong. here is the code that pulls the image onto the page:
imgsize.php?w=50&img=images/img4a4139773dbdf.jpg
the image is stored on the server and the url is placed in a mysql database.
Any help would be appreciated
thanks,
Kenny
Sorry to post again but I really have the need to pull images from the admin/images/ on my server by pulling in the url from the mysql database like so:
<img src="” alt=”image”>
but I’m not sure how to implement your code so it automatically proportionally scales the images that get uploaded to the images/ folder and displayed on the main site.
Thanks,
Kenny
I can’t get this to display the image. It seems easy enough but won’t work
Hello Mike,
I like your script! thanks for providing it.
I am trying to integrate it with a forums upload image class and I am having some trouble.
in the forum upload img class there is a check to see if the image is to wide – so I put your code right after that:
if ($width > $fbConfig->imagewidth) {
//imageUploadError(_IMAGE_ERROR_WIDTH . ” (” . $fbConfig->imagewidth . ” pixels”);
$img = $imageLocation; //$_GET['img'];
$percent = $_GET['percent'];
$constrain = 1; //$_GET['constrain'];
$w = 350; //$_GET['w'];
$h = 500; //$_GET['h'];
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
// autocompute width if only height is set
$w = (100 / ($sh / $h)) * .01;
$w = @round ($sw * $w);
} elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
// get the smaller resulting image dimension if both height
// and width are set and $constrain is also set
$hx = (100 / ($sw / $w)) * .01;
$hx = @round ($sh * $hx);
$wx = (100 / ($sh / $h)) * .01;
$wx = @round ($sw * $wx);
if ($hx < $h) {
$h = (100 / ($sw / $w)) * .01;
$h = @round ($sh * $h);
} else {
$w = (100 / ($sh / $h)) * .01;
$w = @round ($sw * $w);
}
}
}
$im = @ImageCreateFromJPEG ($img) or // Read JPEG Image
$im = @ImageCreateFromPNG ($img) or // or PNG Image
$im = @ImageCreateFromGIF ($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
//$message = print_r( $width , TRUE );
//trigger_error( $message, E_USER_ERROR );
if (!$im) {
// We get errors from PHP's ImageCreate functions…
// So let's echo back the contents of the actual image.
readfile ($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor ($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled ($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
// Output resized image
@ImageJPEG ($thumb);
}
nothing happens though?? – any ideas ?
I see that your code is returning the path but no image is actually being created right?
great script. thanks a million!
can you help me resize my photos so that it view in thumbnail….
Untitled Document
name = $file; // Get the image info.
$list[] = $file; // Add the info to the list array.
}
}
}
closedir($dir); // Close the directory
function hasValidExtension($file){ // Check to make sure a file has a valid extension.
global $valid;
$dot = strrpos ($file, “.”);
if ($dot === false){
return false;
}
$ext = substr ($file, $dot+1, 4);
foreach ($valid as $value){
if ($ext == $value){
return true;
}
}
return false;
}
?>
$height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}
//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);
//returns the new sizes in html image tag format…this is so you
//can plug this function inside an image tag and just get the
return “width=\”$width\” height=\”$height\”";
}
?>
<?php
foreach ($list as $image){
echo " \n”;
}
?>
man i found a solution to rezise very large files or images, just add this line to the next version:
ini_set ( “memory_limit”, “40M”);
below:
header (“Content-type: image/jpeg”);
or up, in my case i added below, thanks a lot, your script is great but with this line should work better, see you!
HI Mike,
Im having trouble using your script, wondering if you can help me please. I’ve downloaded your script and saved it in my folder called imgsize.php. I’ve referenced the images in my code to use your script, but they do not display.
This is the line of code I’m trying use <img src="imgsize.php?w=200&img=/OO_online/image/Garden.jpg"
I've gone to the top url and typed in the following http://localhost/OO_online/image/Garden.jpg which displays my original image.
When I type http://localhost/OO_online/imgsize.php?w=30&img=OO_online/image/Garden.jpg I get the following errors
Notice: Undefined index: percent in C:\inetpub\wwwroot\OO_online\imgsize.php on line 29
Notice: Undefined index: constrain in C:\inetpub\wwwroot\OO_online\imgsize.php on line 30
Notice: Undefined index: h in C:\inetpub\wwwroot\OO_online\imgsize.php on line 32
Warning: Division by zero in C:\inetpub\wwwroot\OO_online\imgsize.php on line 49
Warning: readfile(OO_online/image/Garden.jpg) [function.readfile]: failed to open stream: No such file or directory in C:\inetpub\wwwroot\OO_online\imgsize.php on line 82
Anyhelp much appreciated – gd is on, version 2.034 is enabled.
Jalz
So, you haven’t responded to comment Number 202. How to avoid this vulnerability?
Hi Mike!!
Tks for your code, it’s what I need, but… it seems it doesn’t work: my need is a little bit complicated, because I need to get the image from a field of the post. So I tried to do a “merge” of
imgsize.php?w=50&h=100&constrain=1&img=path/to/image.jpg
and my original code to get images from posts
have_posts()) : $recent->the_post();?>
<a href="” rel=”bookmark”><img width="234" height="120" src="ID, ‘left feature’, $single = true); ?>” alt=”ID, ‘Theme Name’, true); ?> Thumbnail” />
This is what I wrote:
have_posts()) : $recent->the_post();?>
<a href="” rel=”bookmark”>ID, ‘left feature’, $single = true); ?>
The result is unexpected ‘=’ on the line of my code.
Maybe you can help me. Thank you a lot.
))
Bye
Sorry, what I wrote is:
have_posts()) : $recent->the_post();?>
<a href="” rel=”bookmark”>ID, ‘left feature’, $single = true); ?>
Suggestions?
<– have_posts()) : $recent->the_post();?>
<a href="” rel=”bookmark”>ID, ‘left feature’, $single = true); ?>
–>
Sorry, it seems that I can’t wrote php code on the comments, it’s wrong. Please send to me an e-mail so I can send to you the code.
Bye
thanks for share your work!
The script work like a charm!
I use it to solve an issue much discussed around “Magazeen Wordpress Theme”, a problem with thumbnails in the “Dock” header.
I’ll write my experience around this, i’m sure some Magazeen user is gonna read this..
For people who still having problems with Dock Thumbnails in “Magazeen Wordpress Theme” I found a solution, thanks Mike Lopez script!
Instead of using “TimThumb.php” I use “imgsize.php” Mike Lopez script (http://tech.mikelopez.info/2006/03/02/php-image-resize-script/)
Upload imgsize.php in the template directory (where “TimThumb.php” was)
Then, modify the line codes in the index.php, header.php to match with the new script syntax.
FOR EXAMPLE… in “header.php” where you have:
“<img src="/timthumb.php?src=ID, “image_value”, true ); ?>&w=69&h=54&zc=1″ alt=”" />”
you have to replace that with:
“<img src="/imgsize.php?w=69&h=54&img=ID, “image_value”, true ); ?>” alt=”" />”
To work, i don’t have to create a folder with CHMOD 777, it’s not necessary (i didn’t do it and it work fine, by the way i don’t know where image are saved on the fly jejeee… i saw other script using a folder to save the resized images)
Thanks again Mike, I’ll be glad if you can leave a comment around what I’ve said about the folder that other scripts use for store the resized images.
Adeux!
I know it’s been a while since you wrote this script Mike, but I still figured I should say thanks because it is tremendously helpful and useful! Great work man.
Yeah, this script is really handy. Thanks Mike!
I am having some difficulty with it though… what I’m trying to do is resize an image in a folder *outside* the root folder.
For example:
My site’s root folder can be found at: http://www.fullcirclemagazine.co.za/
and at: /home/user/public_html/ <– public_html being the root.
What i need to do is use the resizing script on
an image file located at: /home/user/private_folder/image.jpg
is this possible?
Any help will be very much appreciated!!
To work, i don’t have to create a folder with CHMOD 777, it’s not necessary (i didn’t do it and it work fine, by the way i don’t know where image are saved on the fly jejeee… i saw other script using a folder to save the resized images)
Thanks again Mike, I’ll be glad if you can leave a comment around what I’ve said about the folder that other scripts use for store the resized images.
H I had the same problem as in post 111:
“The only problem I found is that it doesn’t show pictures with spaces (or %20) in the file name. Is there a solution for this issue?”
and the suggestion in post 112 of using urldecode() also did not work for me – nor did rawurldecode or urlencode or anything else, untll I noticed that if you just paste in your url to the file as $img = then it works – seems that in some way grabbing it via GET interferes – though it shouldn’t.
easy solution was to use str_replace() in the file to replace all empty spaces in $_GET['img'] with” %20″ and then it worked fine.
Very nice feature, easy to use!
Do you also have a script that just stores an uploaded file resized?
Thanks!
Hi nice script… but the image stretches when both the height and width is given. I need the image to keep the dimension and a background color should fill the space if the width is less. is there any script available?
Regards
Amjath
You can modify the script so that you position the newly created resized image on another image which contains the background color you want. Can’t go into details but I think there are some examples of it in the image functions part of the PHP manual.
Hi,
I am trying to use the code for a number of images instead of one image. something like this:
<img src="imgsize.php?percent=50&img=”/>
but I am not sure how to ‘word’ the img= part of the code.
It is supposed to be an echo of the larger image of choice ($screen) from the blog post.
(this code is written into the php of the index)
thanks
Catherine