PHP Image Resize Script


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.

[ads shoppingads computer]

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.



March 2, 2006 · Posted in Technology  
    

Comments

244 Responses to “PHP Image Resize Script”

  1. bunny on March 3rd, 2006 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.

  2. Terry on March 19th, 2006 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?

  3. Mike Lopez on March 19th, 2006 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

  4. Terry on March 19th, 2006 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).

  5. Mike Lopez on March 19th, 2006 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.

  6. Mike Lopez on March 19th, 2006 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!

  7. Terry on March 19th, 2006 8:18 pm

    ::awesome::

    This works perfectly. Blogging about it now.

    Thanks very much for your help Mike :) .

  8. Mike Lopez on March 19th, 2006 8:44 pm

    No worries! My pleasure!

  9. Diwa del Mundo on March 22nd, 2006 12:59 am

    Very cool script! Keep up the good work! :-D

  10. Brett on March 30th, 2006 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

  11. Mike Lopez on March 30th, 2006 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

  12. Terry on March 31st, 2006 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!

  13. conner on April 7th, 2006 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

  14. Mike Lopez on April 7th, 2006 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

  15. todd travaglini on April 7th, 2006 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

  16. Mike Lopez on April 8th, 2006 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

  17. rua on July 14th, 2006 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

  18. Mike Lopez on July 14th, 2006 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.

  19. Mike Lopez on July 14th, 2006 3:28 pm

    rua, i’m quite confused of what you want to do. could you please explain?

  20. Luis on November 28th, 2006 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

  21. Luis on November 28th, 2006 7:35 am

    Ok… I think I have done it…!!!

    No more help needed…

    Thanks for your script! It’s amazing

  22. Alan Rabello on December 3rd, 2006 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. :)

  23. Mike Lopez on December 4th, 2006 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

  24. Joe on December 13th, 2006 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

  25. Jeff on December 13th, 2006 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?

  26. Mike Lopez on December 13th, 2006 6:05 pm

    Jeff, pulling names from the database would be fine provided that the url you are passing to the script is correct.

  27. Mike Lopez on December 13th, 2006 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. :D

  28. Jeff on December 13th, 2006 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.

  29. Mike Lopez on December 13th, 2006 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.

  30. Jeff on December 13th, 2006 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.

  31. Mike Lopez on December 13th, 2006 7:39 pm

    Jeff, please paste here the URL that you placed in your browser’s address bar.

  32. Mike Lopez on December 13th, 2006 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?

  33. Sam on December 15th, 2006 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!

  34. Mike Lopez on December 15th, 2006 11:59 am

    Hi Sam, how did you use the script?

  35. Sam on December 16th, 2006 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?

  36. Sam on December 16th, 2006 12:04 pm

    OK… ummm how do i post my code that i used? It keeps deleting it out of my comment…

  37. Tomer on December 16th, 2006 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!

  38. Mike Lopez on December 16th, 2006 7:03 pm

    Sam,

    Just don’t include the greater than and less than signs. :)

    Example: img src=”imgsize.php…”

    Mike

  39. Sam on December 17th, 2006 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?

  40. Jerry on December 23rd, 2006 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

  41. Mike Lopez on December 23rd, 2006 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];

  42. BrettH on January 2nd, 2007 7:39 pm

    Nice one,

    Thanks very much for this really easy to use yet very effect script.

    Brett

  43. James on January 4th, 2007 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

  44. Mike Lopez on January 8th, 2007 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

  45. Phil on January 12th, 2007 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?

  46. Joseph on January 22nd, 2007 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?

  47. Mike Lopez on January 23rd, 2007 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.

  48. Robin on January 30th, 2007 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.

  49. Matt on February 1st, 2007 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.

  50. Matt on February 1st, 2007 7:42 pm

    Thanks Mike. I’ve figured it out

    in HTML you use the tag like this…

    Many thanks!

  51. Mike Lopez on February 1st, 2007 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

  52. martin on February 16th, 2007 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!!!

  53. waqas on February 17th, 2007 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.

  54. bidmyspace on February 18th, 2007 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!

  55. Mike Lopez on February 22nd, 2007 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.

  56. dhana on March 6th, 2007 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??

  57. Janos on April 3rd, 2007 4:03 am

    tnx — PHP Image Resize Script

  58. jonathan on April 7th, 2007 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

  59. Nico on April 7th, 2007 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!!

  60. Mike Lopez on April 7th, 2007 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.

  61. vincent on April 12th, 2007 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…

  62. Duncan on April 16th, 2007 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?

  63. Jonny on April 18th, 2007 3:17 am

    Realy nice script.
    Fits my site realy well.

    Thanks for great howto and great job with script.

    Thanks
    Jonny Larsson

  64. David Horn on May 15th, 2007 6:07 pm

    Great script – thank you … now to be seen in action on http://www.fuzzbo.com! Many thanks.

  65. Issam in Rio on July 14th, 2007 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);
    }
    }

    ?>

  66. John Smart on August 3rd, 2007 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?)

  67. kris on August 5th, 2007 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

  68. kris on August 5th, 2007 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

  69. Teerock on August 6th, 2007 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.

  70. Teerock on August 6th, 2007 8:40 pm

    Perhaps I should try my code again.

    ” ?>” />

  71. Teerock on August 6th, 2007 8:41 pm

    Well this is interesting… I’m going to leave off the opening ” ?>” />

  72. Teerock on August 6th, 2007 8:42 pm

    “” ?>” />”

  73. Teerock on August 6th, 2007 8:43 pm

    I give up on trying to post my code…

  74. The Blogger on August 7th, 2007 5:08 pm

    Hi teerok, try replacing the < and the > with [ and ]

  75. The Blogger on August 7th, 2007 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

  76. SoulSmasher on August 12th, 2007 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??

  77. Nile on August 14th, 2007 12:15 am

    Is it possible to adjust the JPEG compression level of the output image?
    Great script, thank you!!

  78. David Rose on August 20th, 2007 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.

  79. Comment Blast on August 21st, 2007 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.

  80. Randall on September 11th, 2007 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?

  81. Brian on October 13th, 2007 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.

  82. Marco Pragliola on October 15th, 2007 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

  83. Marco Pragliola on October 15th, 2007 2:01 am

    Maybe my post got cut… last lines are:
    if (isset($q) AND $q>=0 AND $q

  84. Marco Pragliola on October 15th, 2007 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);

  85. m4tt on October 25th, 2007 4:22 am

    I love your script, saved me alot of time! ! !

  86. John Preston on November 1st, 2007 12:17 am

    I’m using simply special software for photo resize.

  87. The Blogger on November 1st, 2007 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.

  88. Vasilis on November 6th, 2007 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?

  89. The Blogger on November 6th, 2007 8:13 am

    Hi, sorry haven’t had time to look at the code but perhaps a call to urldecode would fix it?

  90. Vasilis on November 6th, 2007 3:54 pm

    Unfortunately, urldecode($_GET['img']) doesn’t do anything…

  91. The Blogger on November 10th, 2007 10:07 am

    Randy,

    You have to rename it to imgsize.php and not imgsize.phps

    Mike

  92. Karthik on November 13th, 2007 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

  93. Dave on November 14th, 2007 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

  94. The Blogger on November 14th, 2007 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

  95. Karthik on November 15th, 2007 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

  96. Karthik on November 15th, 2007 2:53 am

    height new: $new_height”;
    echo ‘

    ‘;

    ?>

  97. Dave on November 15th, 2007 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

  98. The Blogger on November 27th, 2007 3:15 am

    Hi Kate,

    stream_get_contents only works in PHP5

    try using file_get_contents instead.

    Mike

  99. The Blogger on December 5th, 2007 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

  100. Momentis Man on January 3rd, 2008 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

  101. Jordan on January 4th, 2008 11:20 am

    Thanks for sharing! Saved me several hours of work and pounding angrily on my keyboard.

  102. Marlee Brown on January 9th, 2008 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

  103. Carlos on January 15th, 2008 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!

  104. Zach on January 28th, 2008 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…..

  105. Bwebmasta on February 15th, 2008 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….

  106. Gary on February 21st, 2008 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!

  107. Rafafas on March 7th, 2008 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 !!!

  108. kristian on April 17th, 2008 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

  109. Victor on April 17th, 2008 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!! =(

  110. Victor on April 17th, 2008 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

  111. Mike Lopez on April 17th, 2008 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.

  112. Victor on April 18th, 2008 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!

  113. Mike Lopez on April 18th, 2008 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

  114. Budi Dermawan on May 10th, 2008 2:09 am

    thank you for the script.
    your script very usefull.

  115. Mike Lopez on May 17th, 2008 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

  116. Brian Marshall on May 17th, 2008 4:13 am

    Will do. My little tech army is looking into in now. Should have solution soon.

  117. Mike Lopez on May 17th, 2008 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

  118. Brian Marshlal on June 19th, 2008 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.

  119. Wilhelm on June 22nd, 2008 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.

  120. Mike Lopez on July 17th, 2008 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 :)

  121. Billa Rajinikar on July 25th, 2008 2:34 pm

    exalent code…………………………………….
    thanks brother……………………
    i am from india………………………………………..

  122. Jake on August 6th, 2008 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?

  123. Mike Lopez on August 6th, 2008 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

  124. TJ F on August 10th, 2008 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.

  125. dominic on August 11th, 2008 6:55 pm

    this is great… more power…..

  126. Edward Coleridge Smith on August 14th, 2008 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

  127. yas on August 27th, 2008 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..

  128. Mike Lopez on August 27th, 2008 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

  129. aED on September 1st, 2008 10:29 am

    Very nice Thanks for sharing this will help alot….

  130. Sean on September 11th, 2008 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
    // 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 >> 8) & 0xFF);
    $bOrig = ($rgbOrig & 0xFF);

    $rgbBlur = ImageColorAt($imgBlur, $x, $y);

    $rBlur = (($rgbBlur >> 16) & 0xFF);
    $gBlur = (($rgbBlur >> 8) & 0xFF);
    $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)) {
    $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 >> 8) & 0xFF);
    $bOrig = ($rgbOrig & 0xFF);

    $rgbBlur = ImageColorAt($imgBlur, $x, $y);

    $rBlur = (($rgbBlur >> 16) & 0xFF);
    $gBlur = (($rgbBlur >> 8) & 0xFF);
    $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;

    }

  131. sajjad on September 15th, 2008 10:28 pm

    Thanks for such a good code…

  132. abidjantalk on October 11th, 2008 12:30 pm

    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)){

  133. Steve on October 22nd, 2008 5:07 pm

    Thanks for that – a good script! I’m trying it out now on a new site.

  134. TRo on October 24th, 2008 6:15 am

    Thanks.Great !

  135. Retesh on October 31st, 2008 5:16 pm

    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…

  136. phpnewbie on November 7th, 2008 6:42 pm

    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.

  137. Jk on November 7th, 2008 10:47 pm

    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?

  138. Mike Lopez on November 8th, 2008 6:09 am

    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

  139. Jk on November 8th, 2008 3:28 pm

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

  140. sandisk superspeed USB on November 11th, 2008 12:45 pm

    Thank you for sharing this script. it really helps to re size the image using code.

  141. Jk on November 12th, 2008 1:49 am

    Hi Mike, do you have an answer for the Que above, ‘Coz I am unable to resize it on a server…

  142. Melanie on November 17th, 2008 12:18 pm

    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 :)

  143. MeSoPleased on November 19th, 2008 6:49 am

    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. :)

  144. Reminders on December 6th, 2008 5:04 am

    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.

  145. Mike Lopez on December 19th, 2008 3:55 am

    try passing the full url of the image to the script.

  146. Nash on December 21st, 2008 1:04 am

    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.

  147. Mike Lopez on December 21st, 2008 1:11 am

    Sure Nash! I’ll be definitely glad if you can link back to this site though. :)

  148. Mike Lopez on December 22nd, 2008 1:30 pm

    Great work Nash!

  149. Mike Lopez on December 23rd, 2008 10:09 am

    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

  150. Peter on December 23rd, 2008 10:28 am

    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!

  151. John Hamelink on January 3rd, 2009 5:01 am

    This is awesome! Thanks alot :D

  152. jas on January 11th, 2009 1:16 pm

    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

  153. Mike Lopez on January 12th, 2009 10:01 am

    Actually, it will reduce the size as well.

  154. jas on January 13th, 2009 7:04 pm

    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

  155. jas on January 13th, 2009 7:06 pm

    hi jas

    how can i write php code in the comment box to ask the problem what m i facing

    vineet

  156. Nicko on January 23rd, 2009 8:24 pm

    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?

  157. Mike Lopez on January 26th, 2009 11:41 am

    i tested it in php5 and it works just fine. you have to be sure that GD is also enabled in PHP

  158. salman on February 6th, 2009 3:41 am

    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.

  159. Mike Lopez on February 6th, 2009 9:10 am

    Hi salman,

    Are you sure you’re using my script? I’m asking because my script is not named as you specified.

    mike

  160. Alexandra on February 8th, 2009 3:18 am

    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

  161. Joseph on February 12th, 2009 6:57 am

    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!

  162. Alejandro Hanky on February 13th, 2009 4:34 am

    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.

  163. Nate on February 26th, 2009 11:15 pm

    Thanks for this little class, I’ve used it on a few times and it’s saved my butt!

  164. ARTI on March 11th, 2009 8:32 pm

    Thanks you too much, this is working very good! You are perfect guys.

  165. HURST VANROOJ on March 30th, 2009 8:22 pm

    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?

  166. Mike Lopez on April 1st, 2009 11:42 am

    It reduces the file size too.

  167. Ryan on April 14th, 2009 4:30 am

    [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?

  168. Luis Pichardo on April 16th, 2009 11:31 pm

    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

  169. Unique House Numbers on April 27th, 2009 6:06 am

    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

  170. Ryan on May 12th, 2009 4:31 am

    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?

  171. roman on May 16th, 2009 10:00 pm

    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);

  172. Mike Lopez on May 25th, 2009 9:11 pm

    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

  173. Ryan on May 26th, 2009 11:25 am

    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?

  174. Kenny on June 24th, 2009 12:52 pm

    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

  175. Kenny on June 24th, 2009 12:59 pm

    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

  176. aaron on June 29th, 2009 8:08 am

    I can’t get this to display the image. It seems easy enough but won’t work

  177. Andy on July 1st, 2009 10:39 am

    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?

  178. olurika on July 6th, 2009 6:45 pm

    great script. thanks a million!

  179. quickblack on July 15th, 2009 6:08 am

    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”;
    }
    ?>

  180. abraham on July 17th, 2009 1:20 am

    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!

  181. Gee on July 23rd, 2009 11:46 pm

    So, you haven’t responded to comment Number 202. How to avoid this vulnerability?

  182. bb2 on August 3rd, 2009 7:04 am

    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 ;-) ))

  183. bb2 on August 3rd, 2009 7:06 am

    Sorry, what I wrote is:

    have_posts()) : $recent->the_post();?>
    <a href="” rel=”bookmark”>ID, ‘left feature’, $single = true); ?>

    Suggestions?

  184. bb2 on August 3rd, 2009 7:07 am

    <– have_posts()) : $recent->the_post();?>
    <a href="” rel=”bookmark”>ID, ‘left feature’, $single = true); ?>

    –>

  185. bb2 on August 3rd, 2009 7:10 am

    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

  186. Nick on August 27th, 2009 8:46 am

    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.

  187. sdf on August 31st, 2009 4:50 pm

    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.

  188. Food Recalls on September 9th, 2009 9:36 pm

    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.

  189. Net Toolbox - John on September 16th, 2009 7:28 am

    Very nice feature, easy to use!

    Do you also have a script that just stores an uploaded file resized?

    Thanks!

  190. Amjath on October 14th, 2009 3:45 pm

    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

  191. Mike Lopez on October 15th, 2009 3:18 am

    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.

  192. Catherine on January 14th, 2010 1:54 am

    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

  193. Laurie on March 12th, 2010 5:50 am

    Great script. Wondering if this script can take an image say 200 pixels wide x 100 pixels high….then capture part of that image to create a thumbnail 50 x 50 without compressing image…..so the end result would be a partial view of the original image. hope that makes sense.
    If this script currently does not do this, can you let me know if you would interested in creating it.
    thanks
    Laurie

  194. Mike Lopez on March 16th, 2010 6:05 am

    Nope, it can’t do that.

  195. Trupti Patel on March 21st, 2010 4:07 pm

    nice script..But my problem is when user do right click and save image it is display file name like imgsize.php…Is there any way to display original file name instead of php file name when user want to save it???

  196. Vishu on March 26th, 2010 3:12 pm

    Great script!…works perfectly in my collg project..thanks mike! =]

  197. Hash on April 15th, 2010 11:49 pm

    IT DOESN’T WORK!

  198. jean on April 22nd, 2010 8:50 am

    Hi, I’m newbie to this problem…I have a form with a browse for file button. The button should upload an image only. The image could be of any size. Now I want to save the image to mysql database but before the image will be stored to the database I want a php script that split up the image into 1 KB chunks of data and then save it to the database table as 1 KB.
    Any help would be appreciated…Thank you.

Leave a Reply