PHP: Upload and resize image script

January 29th, 2008 by jason

imageresize.jpg

This tutorial will show you how to use this script to upload an resize images. If you have not read my tutorial on image uploading I would suggest you also check it out here. I have also supplied my code for download and use at the end of this tutorial.



The code makes use of the PHP GD library which must be installed and running for this script to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<form action="<?php echo $_server['php-self'];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">
        <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />
        <button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>
</form>
<?php
        if(isset($_POST['submit'])){
          if (isset ($_FILES['new_image'])){
              $imagename = $_FILES['new_image']['name'];
              $source = $_FILES['new_image']['tmp_name'];
              $target = "images/".$imagename;
              move_uploaded_file($source, $target);
 
              $imagepath = $imagename;
              $save = "images/" . $imagepath; //This is the new file you saving
              $file = "images/" . $imagepath; //This is the original file
 
              list($width, $height) = getimagesize($file) ; 
 
              $modwidth = 150; 
 
              $diff = $width / $modwidth;
 
              $modheight = $height / $diff; 
              $tn = imagecreatetruecolor($modwidth, $modheight) ; 
              $image = imagecreatefromjpeg($file) ; 
              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
 
              imagejpeg($tn, $save, 100) ; 
 
              $save = "images/sml_" . $imagepath; //This is the new file you saving
              $file = "images/" . $imagepath; //This is the original file
 
              list($width, $height) = getimagesize($file) ; 
 
              $modwidth = 80; 
 
              $diff = $width / $modwidth;
 
              $modheight = $height / $diff; 
              $tn = imagecreatetruecolor($modwidth, $modheight) ; 
              $image = imagecreatefromjpeg($file) ; 
              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 
 
              imagejpeg($tn, $save, 100) ; 
            echo "Large image: <img src='images/".$imagepath."'><br>"; 
            echo "Thumbnail: <img src='images/sml_".$imagepath."'>"; 
 
          }
        }
?>

Basically, what the above does is upload the file into a folder called “images”, from there the image is resized and a smaller thumbnail also created. You can adjust the width of the image resize at the $modwidth variable, the first being for the larger image and the second for the thumbnail. The height is automatically worked out depending on the width, you can also manually set this in the $modheight variable.

Hope this code helps you, if you have any questions please leave a comment. The code is available for download bellow.

upload_resize.zip

Posted in General Opensource

58 Comments

  1. Daniel

    Hello,

    Do you have a modification to upload more than 1 image? We want to use your script for 5 or 6 image uploads.

    Thanks!

  2. jason

    @Daniel

    Thats a very easy mod, simply create as many upload boxes as you need then put the processing part of the code in a while loop and feed the imagename in :)

  3. Gary Greenberg

    Hey guys,
    I have changed the above code a bit to allow for it to work as part of a function. You may do a loop through the images that you wish to be resized by doing it this way. Hope it helps. Thanks for the original code jason.

    <?php

    error_reporting(0); //Switches off error warnings

    function create_image($formname, $imagename, $exts, $mydir, $imagewidth, $thumbwidth)
    {

    if (isset ($_FILES[$formname])) //Checks if the file has been set
    {
    //$imagename = $_FILES[$formname]['name'];
    $ext=explode(”.”,$_FILES[$formname]['name']); //Splits a string into an array with a full stop delimiter
    $ext=strtolower($ext[1]); //converts the extension to lowercase
    $imagename=”$imagename.$ext”; //filename.EXTENSION

    if (in_array(strtolower($ext),explode(”|”,strtolower($exts)))) //Checks if extension is valid
    {

    if (!file_exists($mydir)) //Create if doesn’t exist (images)
    mkdir($mydir);

    if (!file_exists(”$mydir/_thumb”)) //Create if doesn’t exist (thumbs)
    mkdir(”$mydir/_thumb”);

    $source = $_FILES[$formname]['tmp_name'];
    $target = “$mydir/$imagename”;
    move_uploaded_file($source, $target); //moves file

    $imagepath = $imagename;

    //### Part One

    $save = “$mydir/$imagepath”; //This is the new file you saving
    $file = “$mydir/$imagepath”; //This is the original file

    list($width, $height) = getimagesize($file); //Assigns the height and width of the image by making use of the file

    $modwidth = $imagewidth; //Image width is set as the mod width

    $diff = $width / $modwidth; //Image width difference is checked against the the max and image widths

    $modheight = $height / $diff; //Image height is set as the mod height
    $tn = imagecreatetruecolor($modwidth, $modheight); //Create a new true colour image
    $image = imagecreatefromjpeg($file); //Creates a new image from the file
    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); //Copy’s and resizes the image to the respective size

    imagejpeg($tn, $save, 100); //Outputs image to the browser or a file

    //### Part Two

    $save = “$mydir/_thumb/$imagepath”; //This is the new file you saving
    $file = “$mydir/$imagepath”; //This is the original file

    list($width, $height) = getimagesize($file); //Assigns the height and width of the image by making use of the file

    $modwidth = $thumbwidth; //Mods the size fo the thumb to the max width

    $diff = $width / $modwidth; //Image width is set as the mod width

    $modheight = $height / $diff; //Image height is set as the mod height
    $tn = imagecreatetruecolor($modwidth, $modheight); //Create a new true colour image
    $image = imagecreatefromjpeg($file); //Creates a new image from the file
    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); //Copy’s and resizes the image to the respective size

    imagejpeg($tn, $save, 100) ; //Outputs image to the browser or a file
    //echo “Large image: “;
    //echo “Thumbnail: “;
    }
    }
    }
    ?>

  4. Gary Greenberg

    Hey again guys,
    I have created two versions of a loop you can use for the above function to run numerous times for multiple files on a form. The files will be saved in the directory “posts” within the subdirectory of the date and time of the post thus making it ‘unique’. Good luck!

    $mydir=”../images/posts/$submitdatetime”; //Directory is set as the submission date and time

    //—-

    if(!isset($_FILES) && isset($HTTP_POST_FILES))
    $_FILES = $HTTP_POST_FILES;

    include (”process_images.php”); //File where the above function is located

    //—-

    for ($x=1; $x<=5; $x++) //Total images is five
    {
    if ($x==1)
    $formname=”primary_image”; //Image name is set as primary_image for the first image
    else
    $formname=”image$x”; //Image name is set as image02, image03 when x is not run for the first image

    create_image($formname, sprintf(”%02d”,$x), “jpg|jpeg|gif”, $mydir, 300, 150); //Inputs imagename with trailing zero if < 10
    }

    //———————————-
    //OR YOU CAN DO SOMETHING SIMPLER
    //———————————-

    for ($x=1; $x<=10; $x++) //Total images is ten
    {
    $formname=”image$x”; //Image name will be image01, image02, image10

    create_image($formname, sprintf(”%02d”,$x), “jpg|jpeg|gif”, $mydir, 300, 150); //Inputs imagename with trailing zero if < 10
    }

  5. mmx97

    Thank you for publish this code
    it’s very sample

    But this code for jpg & jpeg only
    what about

    Gif and Bmp

    Thank you

  6. mike

    hey is it possible to have this store the thumbnail in database??

  7. jason

    @mmx97
    You can get this to work on .gif and .bmp.
    Just use imagegif() or imagebmp() instead of imagejpeg(), depending on what image type you are working with.

  8. jason

    @mike, yes google ’storing image as blob’

  9. Vince

    @mike
    I got my script to save all the conversions (3 in total) to be saved in a mysql db.

    Her’s my code right after this last line:
    imagejpeg($tn, $save, 100) ;

    //DB Insertion

    mysql_query (”UPDATE about SET yourimagename=’$imagepath’ WHERE id=’$id’”);

    I hope it helps.

    BTW Jason, I am new to php and mysql, I don;t really know how to create a “while loop” in order to have more than 1 image be uploaded at once.
    If you could please post a sample referencing your script, that would be great.
    I really did not understand Gary’s.

    Again, I am very new and couldn’t get it to work. ;-s

  10. Jeff

    Many thanks for the simple script. It’s exactly what I’ve been looking for. Many script snippets I’ve looked looked a bit too complicated or outdated (lack of move_uploaded_file function or no GD)

    Cheers!

  11. paul

    heloo,
    am just a newbie thanks 4 the code..
    how will i get back the code of the image am uploading…
    like if i upload dog.jpg
    i must get back the url
    as http://mydomain.com/images/dog.jpg
    which can be copied..
    how to echo that out? plz help

  12. Alfonso

    I have 2 simple questions about this great script:

    1. How can I delete original file after create thumbnails?

    2. If original width file is 300 px for example and thumbnail must be 400 px. What must we do to skip this step?

  13. Matt

    Hey, can you please explain how to mod the script for multiple uploads.I’m quite new to PHP and I’m not sure how to phrase the while loop or where to place it..

  14. Marko

    Great script! Please help….

    I am trying to basically do this, http://www.mclovinidmaker.com/. It lets you upload a photo and replace a designated area of an image with your own image. How would I do this?

    Any help would be much appreciated!

    Thanks!

  15. prethum

    hi i have a problem thisworks fine on local host but when i put it on webserver it does not do any thing any sujestions plz
    i have a root folder called images on my remote server can any body guide me how how to do i have a form where users can uplaod a image i want to store the path on mysal and image on a folder where i can retive the image back to my webpage can any body help me with this

  16. Kirk

    Is it possible to set a fixed size, so that the image wont be resized in proportion?

    For example if I need each thumbnail created 75px by 75px. No more or no less.

  17. rman

    Hello,
    I am a bit new and am having a bit of trouble. I really appericate the code above but I seem to have run into a stamping point. as I have diplayed the image name via the echo code, I would like to populate that text into my data base as well, and I seem to be of no aval.

    Please help

  18. Tim

    Howdy, thanks for the script - hopefully very handy for me.

    However when I am running this on localhost (Mac Apache/1.3.41 (Darwin) PHP/5.2.2) I am finding that the large image files are becoming corrupt but the sml_ files are OK.

    GD library is on but I had to change $_server['php-self'] to $_SERVER['PHP_SELF'] to get it to work at all.

    Any pointers would be appreciated.

    Cheers
    Tim

  19. AAGC

    Hello,
    Aswesome, AWESOME script.

    But I have a little problem. With jpg and gif the thumbnails are created without problems.

    But with bmp and png I can’t get it to work, eventhough i’m using the imagecreatefromwbmp, imagecreatefrompng, imagewbmp & imagepng functions.

    Thanks!!!

  20. Greg

    I too am looking for a way to be able to select the output size of the thumbnails. I know it is a simple form, such as:

    Select a thumbnail size:
    100 x 100
    150 x 150
    200 x 200
    250 x 250
    300 x 300

    But I can’t figure out how to work this into the script. Anyone have some ideas? Thanks in advance.

  21. Greg

    Oops, here is the code I meant to publish, minues the slash and the *:

    /*
    Select a thumbnail size:
    100 x 100
    150 x 150
    200 x 200
    250 x 250
    300 x 300

    */

  22. JD

    Thank you very much from Spain, a very useful script.

  23. Stephan

    Hello,
    Is it possible to convert all file extensions from JPG to jpg? Because I need all file names in lower case.

    Regards from Switzerland,
    Stephan

  24. LINUX, QMAIL Sollutions

    Heja Stephan, do smth similar to:

    after:
    $imagename = $_FILES['new_image']['name'];

    add this line :
    $imagename = strtolower(”$imagename”);

    home that helps, good luck

  25. Doug

    Thanks for a well written and easily modded script.
    I only have one problem - new images with the same name as an old one overwrite the old one.
    I’m storing file names in a MySQL table - I can do a call to get all existing names, but how can I prevent the overwriting, say by adding another digit?

  26. Morgan Daly

    Hello,

    Like Matt. I am having a bit of trouble phrasing the while loop. Can you give us a clue.

    I kind of got this far:
    foreach($_FILES['new_image']['name'] as $value) {
    $imagename = $value; …

    But all I really get is a set errors for each loop.

  27. Morgan Daly

    This is what worked for me in the end. I do hope it saves you the time that I lost. This ones for the noobs, like me. We will be great one day, hang in there bro!
    $max_no_img=2; // Maximum number of images value to be set here

    for($i=1; $i<=$max_no_img; $i++){
    echo “Image $i”;
    }

    foreach ($_FILES["new_image"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
    if (isset ($_FILES['new_image'])){
    $imagename = $_FILES['new_image']['name'][$key];
    $source = $_FILES['new_image']['tmp_name'][$key];
    $target = “images/”.$imagename;
    echo “Imagename: $imagename”;
    echo “Source: $source”;
    echo “Target: $target”;
    move_uploaded_file($source, $target);

    $imagepath = $imagename;
    $save = “images/” . $imagepath; //This is the new file you saving
    $file = “images/” . $imagepath; //This is the original file

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

    $modwidth = 150;

    $diff = $width / $modwidth;

    $modheight = $height / $diff;
    $tn = imagecreatetruecolor($modwidth, $modheight) ;
    $image = imagecreatefromjpeg($file) ;
    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

    imagejpeg($tn, $save, 100) ;

    $save = “images/sml_” . $imagepath; //This is the new file you saving
    $file = “images/” . $imagepath; //This is the original file

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

    $modwidth = 80;

    $diff = $width / $modwidth;

    $modheight = $height / $diff;
    $tn = imagecreatetruecolor($modwidth, $modheight) ;
    $image = imagecreatefromjpeg($file) ;
    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

    imagejpeg($tn, $save, 100) ;
    echo “Large image: “;
    echo “Thumbnail: “;
    }
    }
    }

  28. Morgan Daly

    Hello again,

    I also changed:
    $modwidth = 80;
    $diff = $width / $modwidth;
    $modheight = $height / $diff;

    to (for both instances):
    if ($width <= $height) {

    $modheight = 500;

    $diff = $height / $modheight;

    $modwidth = $width / $diff;

    } else {

    $modwidth = 500;

    $diff = $width / $modwidth;

    $modheight = $height / $diff;
    }
    Now it resizes based on the longest side.

  29. Alex Lopez

    Hi Guys,

    thanks for this script, I just needed the multiple upload and resizing without thumbnail, here is the code if someone need it:

    <?php
    $max_no_img=5; // Maximum number of images value to be set here
    if($_POST){
    for ($x=1; $x<=$max_no_img; $x++) //Total images is ten
    {
    $formname=”image$x”; //Image name will be image01, image02, image3
    $user_id=’user_id’; //To have different name for each file per user in my case.
    create_image($formname, $user_id.’_’.$x, ‘640′);
    }
    }else{
    echo “”;
    echo “”;
    for($i=1; $i<=$max_no_img; $i++){
    echo “Image $i
    “;
    }
    echo “Upload/Resize Image”;
    echo ” “;
    }
    error_reporting(0); //Switches off error warnings
    function create_image($formname, $imagename, $imagewidth)
    {
    $mydir=’images’;//Directory in your server
    $exts =’jpg|jpeg’;
    if (isset ($_FILES[$formname])) //Checks if the file has been set
    {
    $ext=explode(”.”,$_FILES[$formname]['name']); //Splits a string into an array with a full stop delimiter
    $ext=strtolower($ext[1]); //converts the extension to lowercase
    $imagename=”$imagename.$ext”; //filename.EXTENSION
    if (in_array(strtolower($ext),explode(”|”,strtolower($exts)))) //Checks if extension is valid
    {
    if (!file_exists($mydir)) //Create if doesn’t exist (images)
    mkdir($mydir);
    $source = $_FILES[$formname]['tmp_name'];
    $target = “$mydir/$imagename”;
    move_uploaded_file($source, $target); //moves file
    $imagepath = $imagename;
    $save = “$mydir/$imagepath”; //This is the new file you saving
    $file = “$mydir/$imagepath”; //This is the original file
    list($width, $height) = getimagesize($file); //Assigns the height and width of the image by making use of the file

    if($width

  30. Kirsty

    This is a great script, but I have the same query as Kirk and Greg. Is there a way to produce the thumbnail images as a cropped square? Other than that, this is exactly what I need. Thanks!

  31. Mark Williams

    For anyone who wants more control over dimensions.
    I found this script very useful and simple, but needed to create a thumbnail that would fit in a square box, so I modified the code like so:

    $maxlength = 540;
    $maxheight = 540;

    if ($height > $width) {
    $modheight = $maxheight;
    $diff = $height / $maxheight;
    $modwidth = $width / $diff;
    } else {
    $modwidth = $maxlength;
    $diff = $width / $maxlength;
    $modheight = $height / $diff;
    }

    You can change the max height and max width values to whatever you want, and slot that code in in place of the current mod height code (in between the list() command, and the imagecreatetruecolor() command.

  32. Juan Carlos Rois

    Jason. Thanks a lot for this example, it helped me a lot.

    I really appreciate that you take the time to help others and as soon as I’m capable of creating my own scripts, I’ll make sure I pass them along.

    Thanks a million.

    Jnk

  33. Beautiful Ways

    If anyone has problems with this script stopping when uploading large images, try increasing the max_memory limit in php.ini. If your host doesn’t allow you direct access to your php.ini, you can add a line to .htaccess instead.

  34. Nathan

    Dude you rock. This script is great. I’ve been looking for something as simple and effective as this for ages - thanks man!

  35. Chavex

    I need to upload multiple files and resize the images

    i need the full code ………please help me

  36. Zach

    Works great for me, exactly what I need.

    BUT

    Is there a way to make this handle animated gifs? I’d like the output file to remain animated. Currently it comes out with only the first frame.

  37. eduardohet

    There are limits to the maximum size of uploaded image?? Or it depends on the server?
    Thanks for the script.

  38. Danny

    Many thanks for the script works like a treat :D Just what been looking for :)

  39. Billy

    How would I go about only resizing and saving one image, and having that image always saved with the same filename?

    I was able to comment out the thumbnail creation, but when I try to change the image save name, I wind up with two images, one with the original filename and one with the name I choose.

  40. Steve

    Thanks for your script, however, my own issue is the other way round…

    I needed to resize a downloaded image stored on local folder but the image name in database and the path in the script.

    I tried to work around the script but could not get around it. Your help will be appreciated

    Thanks again

  41. David

    I’d like to be able to put the picture/image results into a mysql database. NOT the image itself, but just information like:

    image name of big_pic
    width of big pic
    height of big pic

    image name of sml_pic (thumbnail)
    width of sml_pic
    height of sml_pic

    How would I do this? How do I set the variables (using php) for the information above for database insertion?

    I love the script, just what I’ve been looking for. I need the visitor’s original picture reduced in size using the 350 width and then a thumbnail created. Now I just need figure out how to put the image info into a database using this script.

    I believe I can work in some type of check to ensure it’s an image file and maybe set a file size limit. I don’t know, digital cameras today take pictures with huge file sizes. The average user will not know how or will not want to bother reducing the picture size on the computer first then uploading. That’s why this script is so nice. It does it for them - no fuss for the visitor.

  42. Bradley Hook

    This is a sweet script - worked first time without any configuration or tweaking.

    Nice work Jason.

  43. ARTI

    imagecreatefromjpeg is does not working in my server. I dont understand it. I wonder missing any library in my machine..

  44. Jasen Burkett

    I need to be able to add three input boxes with this.

    I need to add a title, url, image name, and one text box for description.

    the information needs to be saved to a mysql database and the file needs to be saved on the server in a folder.

    is this possible? if so, how.

  45. JJ

    Hey, great script! But I have a minor problem… The server complains on “memory exceeded”, and it doesn’t seem to work unless I set the mem_lim to 40-50, and only 16M is allowed on my server :/

    Is there anyway you can get around this problem?

    Cheers

  46. Tosin

    This script is very helpful but i have an issue, i want to rename the image file before i save it. can anybody help me out.

    Thanks,
    Tosin Orojinmi

  47. helmy

    thanks for the script… it is easy to implement and mod… just what i have been looking for… you just awesome… thanks so much…

  48. Mutant X

    Hi all,
    Thank you for this useful page..

    What about if we want to add watermark to the uploaded image? Could you please write the codes….

    Thank you.

  49. snewpers

    Super script. Finaly one that works without alot of ‘crap’ most others do!

    One thing I can’t figure out / get to wrok is that animated .gifs are not animated anymore once processed. Is there a way to process them as a gif, or, omit gifs from the process completely?

    Thanks a bundle!

  50. Chuck McDonald

    Great script, I am wonder how to insert this into a form for the MySQL database.

    Chuck

  51. Rpap

    hi there,
    i have just briefly gone through the scripting, so proably missed out what it is that i am asking.

    is there a way to set the resized image to 1024 pixels?

  52. randy

    been spending three whole days looking for a script such as this! great and just the right fit for my project!

    thanks Jason!

  53. Luis Garso

    Hey dude thanks for your script !! It works very nice, you rules !!!

  54. William Worley

    adjusted to work with other image types

    replace
    $image = imagecreatefromjpeg($file);

    with
    $file_type = $_FILES['new_image']['type'];
    if($file_type == “image/jpeg” || $file_type == “image/jpg”){
    $image = imagecreatefromjpeg($file);
    }elseif($file_type == “image/x-png” || $file_type == “image/png”){
    $image = imagecreatefrompng($file);
    }elseif($file_type == “image/gif”){
    $image = imagecreatefromgif($file);
    }

  55. David

    How can you separate the thumbnail image information from the newly sized bigger image so that the width and height of both images can be stored in a mysql database? And would

    This is a great script as it takes a picture, resizes it and saves that newly resized image to a folder and then creates a thumbnail image of the larger picture and saves it to a folder also.

    The images size information needs to be put in a database so that when you show it you can include the width and height information in the image tags.

  56. David

    OK, I’ve got so that it goes into a database, but I need to assign the picture with a unique name. This way if someone uploads a different picture with the same name it will not overwrite the existing picture. Also, when I do a check to see if a picture already exists in the database with that name it will be specific to that individual. I would like to assign the user’s id with their picture. For instance, 12_boat.jpg - where 12 is that user’s “user_id”.

    This way when the script performs a check to first see if that image name is already in the database it will be for that person only.

    Many people may have an image named “boat.jpg”, but there will only be one 12_boat.jpg. for user with the user_id - 12.

    I’ve tried this and it doesn’t work:

    $imagename = $_SESSION['user_id'] . ‘_’ . $_FILES['new_image']['name'];

    $source = $_SESSION['user_id'] . ‘_’ . $_FILES['new_image']['tmp_name'];

    I’ve also tried this and it doesn’t work either:

    $imagepath = $_SESSION['user_id'] . ‘_’ . $imagepath;

    So, any idea how to assign the user_id to the image so that it will still create the thumbnail and larger image and put them in their folders?

  57. David

    I’ve worked out the adding user_id to the image name. And I’ve implemented the additional image types feature that William added.

    Now all we need is just one more feature to round this thing off. Using the original example script, how can we perform a check to make sure that the file only has an image extension: .jpg, gif, png, etc.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.