Ajax Image Upload and Resize with jQuery and PHP

Sometimes, it’s better to create your own stuff,  than to rely on some complicated Image Gallery with additional functions which you may not even need. This is a very useful combination of jQuery and PHP script to upload and resize image file without refreshing the page, which means we will be using Ajax to send and request data from server. The script should run out of the box, but it can be modified and extended to suite your needs.

You might also like :
Ajax Image Upload/Resize (Progressbar)
Ajax Multiple Image Upload/Resize (Progressbar)

Image Upload Form

The main page with Ajax upload form, I have included jQuery and jQuery Form plugin to send and retrieve data without refreshing the page, but even if we come across Javascript disabled browser, HTML form should work normally.

 
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
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Upload and Resize with jQuery and PHP</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
 <script>
        $(document).ready(function() {
            $('#UploadForm').on('submit', function(e) {
                e.preventDefault();
                $('#SubmitButton').attr('disabled', ''); // disable upload button
                //show uploading message
                $("#output").html('<div style="padding:10px"><img src="images/ajax-loader.gif" alt="Please Wait"/> <span>Uploading...</span></div>');
                $(this).ajaxSubmit({
                    target: '#output',
                    success:  afterSuccess //call function after success
                });
            });
        });
        function afterSuccess()  {
            $('#UploadForm').resetForm();  // reset form
            $('#SubmitButton').removeAttr('disabled'); //enable submit button
        }
    </script>
 <link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="Wrapper">
<div align="center">
<form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit"  id="SubmitButton" value="Upload" />
</form>
<div id="output"></div>
</div>
</div>
</body>
</html>

Processing Image

This is where uploaded image file is sent for processing and then results are sent back to main page as Ajax response. You can change settings value thumbnail size, image size as per your requirements, one more thing to note here is upload folder path ($DestinationDirectory), make sure folder is writable and path is correct.

Everything is pretty much explained in comment lines, but I want to emphasize few things here, in this script there are two different functions resizeImage() and cropImage(). First one resizeImage() will proportionally resize image, it resizes according to specified size values but final size may vary, depending on original size of image. And the cropImage() will crop image and resize to exact given size no matter what its original size. I have used cropImage() to create thumbnails and for normal resize resizeImage() is used.

 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
<noscript>
<div align="center"><a href="index.php">Go Back To Upload Form</a></div><!-- If javascript is disabled -->
</noscript>
<?php
if(isset($_POST))
{
     //Some Settings
    $ThumbSquareSize        = 200; //Thumbnail will be 200x200
    $BigImageMaxSize        = 500; //Image Maximum height or width
    $ThumbPrefix            = "thumb_"; //Normal thumb Prefix
    $DestinationDirectory   = '/home/websites/uploader/uploads/'; //Upload Directory ends with / (slash)
        //for windows users path starts with drive letter
       //$DestinationDirectory  = 'D:/website/uploader/uploads/'; //Upload Directory ends with / (slash)
    $Quality                = 90;

    // check $_FILES['ImageFile'] array is not empty
    // "is_uploaded_file" Tells whether the file was uploaded via HTTP POST
    if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
    {
            die('Something went wrong with Upload!'); // output error when above checks fail.
    }

    // Random number for both file, will be added after image name
    $RandomNumber   = rand(0, 9999999999);

    // Elements (values) of $_FILES['ImageFile'] array
    //let's access these values by using their index position
    $ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
    $ImageSize      = $_FILES['ImageFile']['size']; // Obtain original image size
    $TempSrc        = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
    $ImageType      = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.

    //Let's use $ImageType variable to check wheather uploaded file is supported.
    //We use PHP SWITCH statement to check valid image format, PHP SWITCH is similar to IF/ELSE statements
    //suitable if we want to compare the a variable with many different values
    switch(strtolower($ImageType))
    {
        case 'image/png':
            $CreatedImage =  imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
            break;
        case 'image/gif':
            $CreatedImage =  imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
            break;
        case 'image/jpeg':
        case 'image/pjpeg':
            $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
            break;
        default:
            die('Unsupported File!'); //output error and exit
    }

    //PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
    //Let's get first two values from image, width and height. list assign values to $CurWidth,$CurHeight
    list($CurWidth,$CurHeight)=getimagesize($TempSrc);

//Get file extension from Image name, this will be re-added after random name
    $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
    $ImageExt = str_replace('.','',$ImageExt);

    //remove extension from filename
    $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);

    //Construct a new image name (with random number added) for our new image.
    $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
    //set the Destination Image
    $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
    $DestRandImageName          = $DestinationDirectory.$NewImageName; //Name for Big Image

    //Resize image to our Specified Size by calling resizeImage function.
    if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
    {
        //Create a square Thumbnail right after, this time we are using cropImage() function
        if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
            {
                echo 'Error Creating thumbnail';
            }
        /*
        At this point we have succesfully resized and created thumbnail image
        We can render image to user's browser or store information in the database
        For demo, we are going to output results on browser.
        */

        echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
        echo '<tr>';
        echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail"></td>';
        echo '</tr><tr>';
        echo '<td align="center"><img src="uploads/'.$NewImageName.'" alt="Resized Image"></td>';
        echo '</tr>';
        echo '</table>';

        /*
        // Insert info into database table!
        mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
        VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
        */


    }else{
        die('Resize Error'); //output error
    }
}

// This function will proportionally resize image
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0)
    {
        return false;
    }

    //Construct a proportional size of new image
    $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
    $NewWidth           = ceil($ImageScale*$CurWidth);
    $NewHeight          = ceil($ImageScale*$CurHeight);
    $NewCanves          = imagecreatetruecolor($NewWidth, $NewHeight);

    // Resize Image
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
        //Destroy image, frees up memory
        if(is_resource($NewCanves)) { imagedestroy($NewCanves); }
    return true;
    }

}

//This function corps image to create exact square images, no matter what its original size!
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
{
    //Check Image size is not 0
    if($CurWidth <= 0 || $CurHeight <= 0)
    {
        return false;
    }

    //abeautifulsite.net has excellent article about "Cropping an Image to Make Square"
    //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
    if($CurWidth>$CurHeight)
    {
        $y_offset = 0;
        $x_offset = ($CurWidth - $CurHeight) / 2;
        $square_size    = $CurWidth - ($x_offset * 2);
    }else{
        $x_offset = 0;
        $y_offset = ($CurHeight - $CurWidth) / 2;
        $square_size = $CurHeight - ($y_offset * 2);
    }

    $NewCanves  = imagecreatetruecolor($iSize, $iSize);
    if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
    {
        switch(strtolower($ImageType))
        {
            case 'image/png':
                imagepng($NewCanves,$DestFolder);
                break;
            case 'image/gif':
                imagegif($NewCanves,$DestFolder);
                break;
            case 'image/jpeg':
            case 'image/pjpeg':
                imagejpeg($NewCanves,$DestFolder,$Quality);
                break;
            default:
                return false;
        }
    //Destroy image, frees up memory
        if(is_resource($NewCanves)) { imagedestroy($NewCanves); }
    return true;

    }

}
?>

That’s it! You can download sample file by clicking download button below, zipped file contains PHP files, css, jQuery form plugin and may be some images. Hope it helps, Good luck!

Download Demo

Related Articles:

Article by on May 7, 2012 Tagged under Tagged under , , . If you like this article, please consider sharing it.

53 Thoughts

  1. hello buddy,
    i really impressd..
    i was searching it here and there at many places but at last i got what i want.
    very cool.. thanx

    can we do one thing more..
    a view page where all images can be shown from database and a delete button to delete single or multiple

  2. Hello,

    i have a problem with your script, when i try to upload a picture in Internet Explorer 8, i have the message “Unsupported File!”.
    Uploading the same picture with Chrome or Firefox is OK.

  3. Hey, great script !

    But (I know, there’s always a but), when resampled my picture is really ugly, squared.
    It seems like it was shrinked to minimum and then expanded to size specified…

    No problem when using your own script on your website.

    PHP Version : 5.3.5
    Extension php_gd2 enabled
    version : bundled (2.0.34 compatible)

    • Well, after investigation, the $jpg_quality variable was not passed to the resizeImage function, so the Jpg quality was set to 0…

      So I added an option in the call to that function, and it works fine !!

  4. I’m getting an error in the
    imagejpeg($NewCanves,$DestFolder,$quality) line!
    ($quality value is 90)

     
    1
    Warning: imagejpeg(/home5/website/uploads/71002439.jpg): failed to open stream: No such file or directory in D:Program Fileswampwwwt3wd6gyhnl-ajax-image-upload-sampleprocessupload.php on line 89
  5. Amazing upload form man.

    Very easy to use but……

    Is there a way of keeping aspect ratio for the thumbnail?

    I have popup full size images over my thumbnails, and it looks funny to click on a square thumb to have a rectangular popup.

    It would be great if you could let me know how to do this.

    It would also be great to be able to add custom width and height to both thumb and full size, and have the script crop the images automatically

    Thanks again for such a great script

    Cheers

  6. Thanks for your greate work, but please its shows me

     
    1
    2
    3
    Warning: imagejpeg() [function.imagejpeg]: Unable to open '/home/websites/uploader/uploads/abiola-494951547.jpg' for writing: No such file or directory in C:wampwwwLagos15Newuplodprocessupload.php on line 129

    Warning: imagejpeg() [function.imagejpeg]: Unable to open '/home/websites/uploader/uploads/thumb_abiola-494951547.jpg' for writing: No such file or directory in C:wampwwwLagos15Newuplodprocessupload.php on line 176

    so please how can i solve this problem please help me.

  7. Amazing, ça fonctionne super.
    Maybe one little thing.
    How to upload transparent .png (and keep transparence ^^)

    U’re the best mate.
    T’es le meilleur mon pote.

  8. abiola October 22, 2012 at 3:59 pm

    Thanks for your greate work, but please its shows me

     
    1
    2
    3
    Warning: imagejpeg() [function.imagejpeg]: Unable to open ‘/home/websites/uploader/uploads/abiola-494951547.jpg’ for writing: No such file or directory in C:wampwwwLagos15Newuplodprocessupload.php on line 129

    Warning: imagejpeg() [function.imagejpeg]: Unable to open ‘/home/websites/uploader/uploads/thumb_abiola-494951547.jpg’ for writing: No such file or directory in C:wampwwwLagos15Newuplodprocessupload.php on line 176

    so please how can i solve this problem please help me.
    Reply ↓

    Saran October 22, 2012 at 7:15 pm

    Try chmod PHP destination folder to 777.

    Pls i didn’t get you, please asist me
    p

  9. Si cela peut aider quelqu’un pour garger la transparence
    If it can help somebody to keep transparence (.gif & .png)

    AFTER:

     
    1
    2
    3
    4
    5
    //Construct a proportional size of new image
    $ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
    $NewWidth  = ceil($ImageScale*$CurWidth);
    $NewHeight = ceil($ImageScale*$CurHeight);
    $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);

    PUT:

     
    1
    2
    3
    4
    5
    //Merci Yves pour la transparence
    imagealphablending($NewCanves, false);
    imagesavealpha($NewCanves,true);
    $transparent = imagecolorallocatealpha($NewCanves, 255, 255, 255, 127);
    imagefilledrectangle($NewCanves, 0, 0, $NewWidth, $NewHeight, $transparent);

    //et merci encore à saaraan ;)

  10. Looks awesome, love the demo and clean simple script -
    I thought ajax for file upload required an iframe, but this just uses a target #div… Is this a new functionality, and if so how far back in browser versions would it support?
    (Also, It runs beautifully on your site, but my local copy running on apache with localhost/… doesn’t work – I get blank images, and no uploads appear in dest folder /uploads/. Any ideas?)

    Don
    have a great day

  11. Your script is simply awesome and work perfect, but is there a way to automatically send the file(s) to the server when they are selected from the user PC? (The aim is not to click on upload button. In fact the user will just have the input file field without the upload button).

  12. Hi
    Brilliant bit of script. Works perfectly first time.
    Question (1)
    If an image has a transparent background before uploading, when the image is re-sampled, it loses the transparent background and is replaced with a black on. Is there a way to keep the original transparent background please.
    Question (2)
    Is there a way to have a separate maxwidth and maxheight?

    Other than that works like a dream.

  13. This is a very, very nice script. I wish I knew how to convert non jpg files to jpg files. I have a photo website and very few people know the difference between png and jpg files. So they upload png files which take up more space. Could this be implemented, and if so, how?

  14. Thanks for your positive and early response expecting such kind of professioanl coordination and support in futer .. you are doing really good work throught this website … Keep it up:)

  15. Thanks for posting this code. It’s great!

    Do you have any recommendations for integrating photo rotation into the code? I am having an issue when I upload directly from an iPhone. Because the iPhone uses the EXIF rotation flag to define how the pic is rotated. Every portrait pic is displayed as rotated left on screen.

    I am looking at some code over at stack overflow to fix the issue but I’m not sure where to integrate it.

    http://stackoverflow.com/questions/3657023/how-to-detect-shot-angle-of-photo-and-auto-rotate-for-website-display-like-desk

    If my link above is striped out, the question at Stack Overflow is #3657023.

Leave a Comment

Get your comment picture from Gravatar.com.
Your email address will not be published. Required fields are marked *