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.jpgResize an image to 50% the size
imgsize.php?percent=50&img=path/to/image.jpgResize an image to 50 pixels wide and autocompute the height
imgsize.php?w=50&img=path/to/image.jpgResize an image to 100 pixels tall and autocompute the width
imgsize.php?h=100&img=path/to/image.jpgResize 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.
March 3rd, 2006 at 11:59 pm
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.
March 4th, 2006 at 1:55 am
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
March 19th, 2006 at 9:24 am
The image quality is awesome, love this script - thank you!
I need something exactly like this that will also resize gif images. Any suggestions?
March 19th, 2006 at 1:29 pm
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
March 19th, 2006 at 7:29 pm
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).
March 19th, 2006 at 7:43 pm
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.
March 19th, 2006 at 7:46 pm
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!
March 19th, 2006 at 8:18 pm
::awesome::
This works perfectly. Blogging about it now.
Thanks very much for your help Mike :).
March 19th, 2006 at 8:44 pm
No worries! My pleasure!
March 22nd, 2006 at 12:59 am
Very cool script! Keep up the good work!
March 30th, 2006 at 11:36 am
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
March 30th, 2006 at 12:56 pm
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
March 30th, 2006 at 10:04 pm
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
March 30th, 2006 at 10:06 pm
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
March 31st, 2006 at 11:16 pm
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!
April 7th, 2006 at 5:57 am
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
April 7th, 2006 at 7:11 am
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
April 7th, 2006 at 3:05 pm
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
April 8th, 2006 at 2:01 am
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
May 7th, 2006 at 6:13 pm
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
July 14th, 2006 at 11:57 am
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
July 14th, 2006 at 3:27 pm
Lucian, just add “error_reporting (0);” without the quotes before the line that says “header (”Content-type: image/jpeg”);” to suppress the notice messages.
July 14th, 2006 at 3:28 pm
rua, i’m quite confused of what you want to do. could you please explain?
November 28th, 2006 at 5:59 am
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
November 28th, 2006 at 7:35 am
Ok… I think I have done it…!!!
No more help needed…
Thanks for your script! It’s amazing
December 3rd, 2006 at 3:06 am
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.
December 4th, 2006 at 11:39 am
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
December 13th, 2006 at 1:07 pm
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
December 13th, 2006 at 5:41 pm
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?
December 13th, 2006 at 6:05 pm
Jeff, pulling names from the database would be fine provided that the url you are passing to the script is correct.
December 13th, 2006 at 6:10 pm
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.
December 13th, 2006 at 6:23 pm
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.
December 13th, 2006 at 6:40 pm
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.
December 13th, 2006 at 7:16 pm
Done that, gives me undefined variable like h, constraint and percentage then give me some gibrish - a jumble of numbers and letters mixed together.
December 13th, 2006 at 7:39 pm
Jeff, please paste here the URL that you placed in your browser’s address bar.
December 13th, 2006 at 7:44 pm
http://localhost/imgsize.php?w=150&img=../uploads/webmaster.jpg
December 13th, 2006 at 8:05 pm
Hi Jeff, the URL was truncated. Could you paste it here without the http part so that it doesn’t get truncated?
December 15th, 2006 at 3:34 am
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!
December 15th, 2006 at 11:59 am
Hi Sam, how did you use the script?
December 16th, 2006 at 12:03 pm
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?
December 16th, 2006 at 12:04 pm
OK… ummm how do i post my code that i used? It keeps deleting it out of my comment…
December 16th, 2006 at 6:27 pm
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!
December 16th, 2006 at 7:03 pm
Sam,
Just don’t include the greater than and less than signs.
Example: img src=”imgsize.php…”
Mike
December 17th, 2006 at 7:22 am
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?
December 18th, 2006 at 6:33 am
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
December 23rd, 2006 at 3:05 am
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
December 23rd, 2006 at 1:03 pm
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.
December 23rd, 2006 at 1:06 pm
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];
January 2nd, 2007 at 7:39 pm
Nice one,
Thanks very much for this really easy to use yet very effect script.
Brett
January 4th, 2007 at 7:12 pm
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
January 8th, 2007 at 9:21 am
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
January 12th, 2007 at 1:02 am
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?
January 12th, 2007 at 1:19 am
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
January 22nd, 2007 at 10:19 pm
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?
January 23rd, 2007 at 2:59 am
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.
January 30th, 2007 at 4:00 am
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.
February 1st, 2007 at 6:22 pm
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.
February 1st, 2007 at 7:42 pm
Thanks Mike. I’ve figured it out
in HTML you use the tag like this…
Many thanks!
February 1st, 2007 at 10:32 pm
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
February 16th, 2007 at 5:26 am
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!!!
February 16th, 2007 at 8:16 am
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
February 17th, 2007 at 8:56 pm
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.
February 18th, 2007 at 7:45 am
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!
February 22nd, 2007 at 12:25 am
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.
February 22nd, 2007 at 9:13 am
@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.
March 6th, 2007 at 8:06 pm
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??
April 3rd, 2007 at 4:03 am
tnx — PHP Image Resize Script
April 4th, 2007 at 11:51 pm
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 ?
April 5th, 2007 at 9:20 pm
Richard, try to include the complete path of house.jpg i.e.
http://localhost/imgsize.php?percent=50&img=/path/to/house.jpg
April 7th, 2007 at 4:00 am
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
April 7th, 2007 at 4:41 am
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
April 7th, 2007 at 9:02 am
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!!
April 7th, 2007 at 9:17 am
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.
April 12th, 2007 at 3:30 am
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…
April 16th, 2007 at 3:26 am
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?
April 18th, 2007 at 3:17 am
Realy nice script.
Fits my site realy well.
Thanks for great howto and great job with script.
Thanks
Jonny Larsson
May 15th, 2007 at 6:07 pm
Great script - thank you … now to be seen in action on http://www.fuzzbo.com! Many thanks.
July 14th, 2007 at 12:30 am
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
July 14th, 2007 at 12:35 am
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);
}
}
?>
August 3rd, 2007 at 1:55 am
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.
August 3rd, 2007 at 1:58 am
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?)
August 3rd, 2007 at 8:16 am
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
August 5th, 2007 at 10:35 pm
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
August 5th, 2007 at 10:36 pm
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
August 6th, 2007 at 8:39 pm
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.
August 6th, 2007 at 8:40 pm
Perhaps I should try my code again.
” ?>” />
August 6th, 2007 at 8:41 pm
Well this is interesting… I’m going to leave off the opening ” ?>” />
August 6th, 2007 at 8:42 pm
“” ?>” />”
August 6th, 2007 at 8:43 pm
I give up on trying to post my code…
August 7th, 2007 at 5:08 pm
Hi teerok, try replacing the < and the > with [ and ]
August 7th, 2007 at 5:12 pm
kris,
the script is designed to work as a standalone script. it appears that you have placed my code inside your code.
mike
August 12th, 2007 at 6:21 am
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??
August 12th, 2007 at 11:32 am
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!
August 14th, 2007 at 12:15 am
Is it possible to adjust the JPEG compression level of the output image?
Great script, thank you!!
August 15th, 2007 at 4:50 am
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']);
August 20th, 2007 at 2:50 am
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.
August 21st, 2007 at 4:43 am
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.
August 21st, 2007 at 5:23 pm
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
September 11th, 2007 at 10:52 pm
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?
September 12th, 2007 at 9:45 pm
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
October 13th, 2007 at 3:42 pm
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.
October 15th, 2007 at 1:59 am
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
October 15th, 2007 at 2:01 am
Maybe my post got cut… last lines are:
if (isset($q) AND $q>=0 AND $q
October 15th, 2007 at 2:03 am
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);
October 18th, 2007 at 9:18 am
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.
October 20th, 2007 at 7:18 am
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.
October 21st, 2007 at 3:56 pm
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
October 25th, 2007 at 4:22 am
I love your script, saved me alot of time! ! !
November 1st, 2007 at 12:17 am
I’m using simply special software for photo resize.
November 1st, 2007 at 12:38 am
@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.
November 6th, 2007 at 6:18 am
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?
November 6th, 2007 at 8:13 am
Hi, sorry haven’t had time to look at the code but perhaps a call to urldecode would fix it?
November 6th, 2007 at 3:54 pm
Unfortunately, urldecode($_GET['img']) doesn’t do anything…
November 9th, 2007 at 12:15 am
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!!!
November 10th, 2007 at 10:07 am
Randy,
You have to rename it to imgsize.php and not imgsize.phps
Mike
November 13th, 2007 at 11:16 pm
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
November 13th, 2007 at 11:27 pm
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
November 14th, 2007 at 7:39 pm
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
November 14th, 2007 at 11:50 pm
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
November 15th, 2007 at 2:53 am
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
November 15th, 2007 at 2:53 am
height new: $new_height”;
echo ‘
‘;
?>
November 15th, 2007 at 2:55 am
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
November 22nd, 2007 at 9:43 pm
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']);
November 27th, 2007 at 3:15 am
Hi Kate,
stream_get_contents only works in PHP5
try using file_get_contents instead.
Mike
December 4th, 2007 at 2:24 pm
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???
December 5th, 2007 at 1:42 pm
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
January 3rd, 2008 at 5:40 am
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
January 4th, 2008 at 11:20 am
Thanks for sharing! Saved me several hours of work and pounding angrily on my keyboard.
January 9th, 2008 at 12:51 am
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
January 15th, 2008 at 8:32 am
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!
January 28th, 2008 at 2:36 pm
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?
January 28th, 2008 at 3:03 pm
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…..
February 15th, 2008 at 5:58 am
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….
February 21st, 2008 at 7:41 am
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!
March 7th, 2008 at 1:30 pm
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 !!!
April 17th, 2008 at 1:15 am
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
April 17th, 2008 at 5:21 am
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
April 17th, 2008 at 8:15 am
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!! =(
April 17th, 2008 at 8:16 am
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
April 17th, 2008 at 9:09 pm
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.
April 18th, 2008 at 12:05 am
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!
April 18th, 2008 at 12:27 am
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
May 10th, 2008 at 2:09 am
thank you for the script.
your script very usefull.
May 17th, 2008 at 3:01 am
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.
May 17th, 2008 at 3:11 am
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
May 17th, 2008 at 4:13 am
Will do. My little tech army is looking into in now. Should have solution soon.
May 17th, 2008 at 9:03 am
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.
May 17th, 2008 at 2:50 pm
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
June 19th, 2008 at 1:52 am
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.
June 22nd, 2008 at 10:15 am
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.
July 17th, 2008 at 11:05 pm
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.
July 17th, 2008 at 11:32 pm
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
July 25th, 2008 at 2:34 pm
exalent code…………………………………….
thanks brother……………………
i am from india………………………………………..
August 6th, 2008 at 9:34 pm
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?
August 6th, 2008 at 11:16 pm
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
August 7th, 2008 at 6:21 pm
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
August 10th, 2008 at 10:59 am
Hi, this script is great, but highly intensive. Is there anyway to improve that and/or implement some sort of caching? Thanks.
August 11th, 2008 at 6:55 pm
this is great… more power…..
August 14th, 2008 at 3:58 am
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
August 27th, 2008 at 1:56 pm
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..
August 27th, 2008 at 5:34 pm
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
September 1st, 2008 at 10:29 am
Very nice Thanks for sharing this will help alot….
September 8th, 2008 at 7:56 pm
#
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???
September 11th, 2008 at 6:07 pm
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;
}
September 15th, 2008 at 10:28 pm
Thanks for such a good code…