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!

Very Nice Script, very straight forward!
thax.
I search for this one! thanks!
Resize Error
dont work currect… its redirect me allways to the php file….
Hi,
How can i handle it with a folder containing images and making thum images by images?
you kan show me example with database ,table structure etc..?
The first 100% complete tutorial! Ant it works on the first try. thank you!
You kan show me delete.php for this script? delete from image from database and folder..
hi it’s fairly easy, use unlink() http://php.net/manual/en/function.unlink.php to delete file and
mysql DELETE statement to delete record from table.
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
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.
hi add :
case ‘image/pjpeg’:
just below :
case ‘image/jpeg’:
should work, thanks for notifying.
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 !!
I’m getting an error *Object has no method ajaxSubmit*
I’m getting an error in the
imagejpeg($NewCanves,$DestFolder,$quality) line!
($quality value is 90)
Hi unfortunately I keep getting ‘RESIZE’ error code every time I try to use it.
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
use resizeImage() function instead of cropImage() while creating thumbnails.
Thanks for your greate work, but please its shows me
2
3
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.
Try chmod PHP destination folder to 777.
I can’t download the files. it does not find anything when I click on it. have you removed it?
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.
abiola October 22, 2012 at 3:59 pm
Thanks for your greate work, but please its shows me
2
3
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
How can I add bmp support?
imagewbmp()
Tnx!
thanks a lot.. this is exactly what i want login using facebook.. I need it for my project.. thank you so much.. done good job.
Si cela peut aider quelqu’un pour garger la transparence
If it can help somebody to keep transparence (.gif & .png)
AFTER:
2
3
4
5
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
$NewWidth = ceil($ImageScale*$CurWidth);
$NewHeight = ceil($ImageScale*$CurHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
PUT:
2
3
4
5
imagealphablending($NewCanves, false);
imagesavealpha($NewCanves,true);
$transparent = imagecolorallocatealpha($NewCanves, 255, 255, 255, 127);
imagefilledrectangle($NewCanves, 0, 0, $NewWidth, $NewHeight, $transparent);
//et merci encore à saaraan
Hi Land Yves
In which function is this code going to preserve transparency please?
merci
Found it
works great thanks
Super script !
Congratulations and thx for sharing
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
I found my issue, it was with the upload path. Once i changed to ‘uploads/’ and had a .htaccess file in there it worked great.
Thanks so much!
dumb hahahha
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).
help me
$ThumbSquareSize = 210*132
need height and Width crop thumb code…
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.
nice ajax upload.
thanks boss.
works great. Don’t forget people to change the path to ‘uploads/’ in processupload.php if it doesn’t work.
Hi any update on this one for us please?
Is there a way to have a separate maxwidth and maxheight?
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?
hi
Excellent tutorail ,
now i ant to know how to prepend the images one after another
This is helping a lot. How can I delete the uploaded image once I refresh the page?
Hi Saran its really nice script but i want to store and reterive image form databases how can i integrate this script with mysql database ?
check-out this post http://j.mp/Xfjj4B
You are a god you saved lots of time for me thank you very much!
this is not resize but croping
Is it possible to upload without re-size ?
Thanks…
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:)
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.