On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.
Live Demo Download Source
PHP and HTML(index.php)
This file holds the basic of file uploading html markup and simple php upload handler.
Resize Function(function.php):
Resize function is based on PHP GD library.
Live Demo Download Source
PHP and HTML(index.php)
This file holds the basic of file uploading html markup and simple php upload handler.
<?php include( 'function.php'); // settings $max_file_size = 1024*200; // 200kb $valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // thumbnail sizes $sizes = array(100 => 100, 150 => 150, 250 => 250); if ($_SERVER['REQUEST_METHOD'] == 'POST' AND isset($_FILES['image'])) { if( $_FILES['image']['size'] < $max_file_size ){ // get file extension $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); if (in_array($ext, $valid_exts)) { /* resize image */ foreach ($sizes as $w => $h) { $files[] = resize($w, $h); } } else { $msg = 'Unsupported file'; } } else{ $msg = 'Please upload image smaller than 200KB'; } } ?> <html> <head> <title>Image resize while uploadin</title> <head> <body> <!-- file uploading form --> <form action="" method="post" enctype="multipart/form-data"> <label> <span>Choose image</span> <input type="file" name="image" accept="image/*" /> </label> <input type="submit" value="Upload" /> </form> </body> </html>
Resize Function(function.php):
Resize function is based on PHP GD library.
/** * Image resize * @param int $width * @param int $height */ function resize($width, $height){ /* Get original image x y*/ list($w, $h) = getimagesize($_FILES['image']['tmp_name']); /* calculate new image size with ratio */ $ratio = max($width/$w, $height/$h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* new file name */ $path = 'uploads/'.$width.'x'.$height.'_'.$_FILES['image']['name']; /* read binary data from image file */ $imgString = file_get_contents($_FILES['image']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); /* Save image */ switch ($_FILES['image']['type']) { case 'image/jpeg': imagejpeg($tmp, $path, 100); break; case 'image/png': imagepng($tmp, $path, 0); break; case 'image/gif': imagegif($tmp, $path); break; default: exit; break; } return $path; /* cleanup memory */ imagedestroy($image); imagedestroy($tmp); }
Hi make sure image uploading is blocked when the file input is empty
ReplyDeleteYeah! We can do it by applying isset($_FILES['image'] or is_uploaded_file($_FILES['image']['tmp_name'] condition
Deleteif(!empty($_FILES)) can even be used to block empty image field...
Deletei couldn't upload images which i taken from my digital camera. i got lots of errors such as
DeleteWarning: getimagesize(): Filename cannot be empty in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 15
Warning: Division by zero in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 17
Warning: Division by zero in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 17
Warning: Division by zero in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 18
Warning: Division by zero in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 19
Warning: Division by zero in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 20
Warning: file_get_contents(): Filename cannot be empty in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 24
Warning: imagecreatefromstring(): Empty string or invalid image in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 26
Warning: imagecopyresampled() expects parameter 2 to be resource, boolean given in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 32
please help me or reply me (sanso13527@gmail.com)
alot of new digital camera's take images in RAW format and they need to be converted to img, jpg, jpeg, png or bmp before they can be uploaded
DeleteThis comment has been removed by the author.
DeleteIts working..
ReplyDeleteThanks!
Is it possible to resize multiple images at same time using this way?
ReplyDeleteGood question! Of course it is possible!
DeleteYou need to add multiple attributable on file input.
For detail see here
how to resize images in shape of ladder ...
ReplyDeleteHey I used class for this. How to resize multiple image using the same code. What part of the PHP code we need to change. Because when i tried to take images in loop, i got error of class can not be re-declared. Please help me off in this. Thanks in advance
ReplyDeletenice code
ReplyDeleteThere is a problem with resize when uploading .PNG image, it shows black image.
ReplyDeleteIts all about transparency!
DeletePlease see this resource: http://stackoverflow.com/questions/32243/can-png-image-transparency-be-preserved-when-using-phps-gdlib-imagecopyresample
Hi, can you tell me how to insert the name of the resized file into a DB? I am trying to insert it but am unsure which variable to use.
ReplyDeleteThanks!
You can store original file name using $_FILES['image']['name'] and rather you can call your file like this way uploads/100x100_yourfilename.jpg
DeleteThanks for the great script, i tried to embed it in to my code but it went wrong and gives error.
Deleteso kindly please have a look how to embed it into my code with out any error.
Thanks in advance.
This is the avatar.php file
http://jsfiddle.net/pgbyL52p/
This is the avatar.html.php form
http://jsfiddle.net/7bfy59u3/
Is there a quick modification that would allow this to respect the aspect ratio of the original file? Currently all images are cropped according to the height and width parameters? Is there a way to set the width to auto?
ReplyDeleteWould like to keep the aspect ratio too, as NativePaul mentioned! Examples?
ReplyDeleteI'm not a PHP expert but once you retun a value form a function what's after is not executed.
ReplyDeleteSo this code is never reached:
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
That is correct. Once a return is reached, the function is exited. The return should ALWAYS (ok, there are few exceptions...) be the last line of a function
DeleteNice! Thankyou for the code..
ReplyDeletedoesn't work in IE8... :(
ReplyDeleteThanks, Well done
ReplyDeletethe code is cropping the image..i should get original image instead of cropping...help me please...
ReplyDeletePerfect Code
ReplyDeletesir, can i send these three resisizes Pics in differnt folder insted sending only one folder "UPLOADS"
ReplyDeletepls reply i really needed this thing
Thx for the code, only one thing tho, whatever it is affter the return won't be executed, so your function isn't cleaning up the memory. Just move the return at the bottom ;)
ReplyDeleteGreat code, can you please tell me how I can change this code, so I can uploade multiple images? And not one by one?
ReplyDeleteKind regards
Nancy De Lange
info@pixelduo.be
while uplodaing image as png it takes black color as in border?what to do now?
ReplyDeletePlease reply to the aspect ratio questions. I'm looking for the answer also.
ReplyDeleteHow can upload this resized image into mysql?please give the code
ReplyDeleteWarning: imagejpeg(uploads/100x100_d90e6063f6246b6033581135e9f81a4c510fa220.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36 <------this error came out when i ply it on the demo, what actually happen ??
ReplyDeleteWarning: imagejpeg(uploads/100x100_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36
ReplyDeleteWarning: imagejpeg(uploads/150x150_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36
Warning: imagejpeg(uploads/250x250_Android.jpg): failed to open stream: No such file or directory in /home/w3bees/public_html/demo/resize-image-while-uploading/function.php on line 36
Image resize while uploading
Ясно
ReplyDeleteFatal error: Call to undefined function resize() in C:
ReplyDeletewhat should i do :( please help me out
Excellent and Good Work.
ReplyDeleteThanks for the great script, i tried to embed it in to my code but it went wrong and gives error.
ReplyDeleteso kindly please have a look how to embed it into my code with out any error.
Thanks in advance.
This is the avatar.php file
http://jsfiddle.net/pgbyL52p/
This is the avatar.html.php form
http://jsfiddle.net/7bfy59u3/
grow up kid. is this what you call RESIZE? At first glance I thought it is a great script. It is doing only a NORTIST crop. Webmechanic kids' silly way of handling images
ReplyDeleteThis is the easiest example -
ReplyDeletehttp://phpforweb.info/upload-and-resize-an-image-using-php/
This script works great on its own, but has anybody been able to merge this with the Multiple File Upload? (http://www.w3bees.com/2013/02/multiple-file-upload-with-php.html) It seems to be more than modifying the file input field within the form. I've added the square brackets to name="image" as well as multiple="multiple", but the script doesn't want to execute the resize function. I've also tried merging the two scripts together, but nothing successful yet.
ReplyDeleteShow me how uploading over 2Mb please..
ReplyDeletewhat code is true?
excellent work...
ReplyDeletekeeep sharing...
Good Script... Helped a lot.
ReplyDeleteFatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 14400 bytes) in C:\wamp\www\updated\test2.php on line 46
ReplyDelete1.0356 99399528 imagecreatetruecolor ( ) ..\test2.php:46
any solutions??
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 14400 bytes) in C:\wamp\www\updated\test2.php on line 46
ReplyDelete1.0356 99399528 imagecreatetruecolor ( ) ..\test2.php:46
any solutions??
great ideas, i've done my script - image resize before uploading with your ideas.
ReplyDeleteThanks Resalat Haque.,
crap. this script is only useful if you really into square images all the time. and you dont want to answer anyone how to respect image aspect ratio? thank you sori
ReplyDeleteplease help me out
DeleteHi , its cropping the image, i dont want cropping , only resizing , ex(image pix is pixel * pixel means i want it in 600*600 with original full image but now its cropping)
Hi , its cropping the image, i dont want cropping , only resizing , ex(image pix is pixel * pixel means i want it in 600*600 with original full image but now its cropping)
ReplyDeleteany easy method available for compress image in php
ReplyDeleteGreat Script! How can I change the outputted file name (rename) to a specific name like filename1.jpg
ReplyDeleteHelpfull...Thank you....
ReplyDelete
ReplyDeleteWeb design company in Pakistan established in
2008 to provide web services like Web Hosting,Web Design, Logo Design, Flash Animations, Web
Development, SEO/SEM
that script solve my problem
ReplyDeletedịch vụ kế toán thuế tại cầu giấy
ReplyDeletedịch vụ kế toán thuế tại thanh xuân
dịch vụ kế toán thuế tại hà đông
dịch vụ kế toán thuế tại long biên
dịch vụ kế toán thuế tại tphcm
dịch vụ kế toán thuế tại bắc ninh
dịch vụ kế toán thuế tại đống đa
dịch vụ kế toán thuế tại tây hồ
dịch vụ kế toán thuế tại ba đình
dịch vụ kế toán thuế tại từ liêm
dịch vụ kế toán thuế tại hai bà trưng
dịch vụ kế toán thuế tại hoàng mai
dịch vụ kế toán thuế tại thanh trì
dịch vụ kế toán thuế tại quận 3
dịch vụ kế toán thuế tại quận thủ đức
dịch vụ kế toán thuế tại quận bình thạnh
dịch vụ kế toán thuế tại quận tân phú
dịch vụ kế toán thuế tại quận 12
dịch vụ kế toán thuế tại quận 11
dịch vụ kế toán thuế tại quận 10
dịch vụ kế toán thuế tại quận 9
dịch vụ kế toán thuế tại quận 8
dịch vụ kế toán thuế tại quận 7
dịch vụ kế toán thuế tại quận 6
dịch vụ kế toán thuế tại quận 5
dịch vụ kế toán thuế tại quận 4
great script. You should clean up the memory before the return :)
ReplyDeleteDapatkan disini , karena Obat Pelangsing slimming Capsule Di Apotik belum tersedia , karena slimming capsule tidak di jual di sembarang temapat termasuk di apotik pun tujuannya untuk menjaga ke aslian produk tersebut, karena sekarang banyak perusahaan yang meniru produk produk herbal sehingga herbal yang asli khasiatnya bisa di rusak oleh produk yang palsu. Untuk itu hati hati dengan slimming capsule
ReplyDeleteand obat vig power capsule
image quality is getting degraded , can you help in managing the same .. i want that image quality doesn't go down.
ReplyDeleteWow! This is really an informative and good code. This post is very good.
ReplyDeletewww.cute-it.com
Loved the script, and I added a lot of great features of my own, including a custom filename before adding it to database, but like others have mentioned, I still think the original image should be maintained, and the aspect ratio should be (optionally) preserved as one of the array options.
ReplyDeleteI have read your blog its very attractive and impressive. I like it your blog.
ReplyDeletePHP Training in chennai | PHP Training Course
PHP Training in chennai | Online PHP Course
how to solve this error in this program
ReplyDelete$files[] = resize($w, $h);
Fatal error: Call to undefined function resize() in C:\xampp\htdocs\New\index.php on line 16
Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.more
ReplyDeletephp jobs in hyderabad.
Those who dont want their image to be cropped, then replace it with this code
ReplyDeletethis worked for me
//do not crop update
$ratio = max($width/$w, $height/$h);
//$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
//$w = ceil($width / $ratio);
/* new file name */
$path = 'songs/'.$width.'x'.$height.'_'.$_FILES['songs']['name'][$key];
$path1 = $width.'x'.$height.'_'.$_FILES['songs']['name'][$key];
/* read binary data from image file */
$imgString = file_get_contents($_FILES['songs']['tmp_name'][$key]);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image,0, 0, 0, 0,$width, $height,$w, $h);
it worked, thanks man
Delete• Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time. Please keep updatingAzure Online Training Hyderabad
ReplyDeleteDid you know that you can easily view the contents of your phone on your TV without a cable? With a screen mirror app you can easily do the screen mirroring from Android to TV. Check out www.screenmirroring.me to find out more.
ReplyDeleteFacebook Video Downloader HD is an Android mobile app that offers the easiest way to download videos from Facebook.
ReplyDelete