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

del.icio.us Digg Technorati StumbleUpon

Posted in General Opensource

28 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.

Leave a Comment

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