Loading Searchbox
9lessons programming blog logo
Monday, March 16, 2009

Upload and Resize an Image with PHP

74 comments
Are you looking for image upload and Resize PHP script. I had developed perfect PHP script it's verify extension, image size and resize image. It's very useful image upload script in web projects to reduces servers space.


Download Script

PHP Code
This script resize an Image into two 60px and 25px. Take a look at $newwidth you have to modify size values.
<?php 

 define ("MAX_SIZE","400");

 $errors=0;
 
 if($_SERVER["REQUEST_METHOD"] == "POST")
 {
        $image =$_FILES["file"]["name"];
 $uploadedfile = $_FILES['file']['tmp_name'];

  if ($image) 
  {
  $filename = stripslashes($_FILES['file']['name']);
        $extension = getExtension($filename);
  $extension = strtolower($extension);
 if (($extension != "jpg") && ($extension != "jpeg") 
&& ($extension != "png") && ($extension != "gif")) 
  {
echo ' Unknown Image extension ';
$errors=1;
  }
 else
{
   $size=filesize($_FILES['file']['tmp_name']);
 
if ($size > MAX_SIZE*1024)
{
 echo "You have exceeded the size limit";
 $errors=1;
}
 
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png")
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else 
{
$src = imagecreatefromgif($uploadedfile);
}
 
list($width,$height)=getimagesize($uploadedfile);

$newwidth=60;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);

$newwidth1=25;
$newheight1=($height/$width)*$newwidth1;
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,
 $width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1, 
$width,$height);

$filename = "images/". $_FILES['file']['name'];
$filename1 = "images/small". $_FILES['file']['name'];

imagejpeg($tmp,$filename,100);
imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}
}
}
//If no errors registred, print the success message

 if(isset($_POST['Submit']) && !$errors) 
 {
   // mysql_query("update SQL statement ");
  echo "Image Uploaded Successfully!";

 }
 ?>



Extention PHP funtion
Finds file extensions.
function getExtension($str) {

         $i = strrpos($str,".");
         if (!$i) { return ""; } 
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

Download Script
Sponsored Links

Recent Posts

Share this post

Subscribe to my feeds

Subscribe
Comments
74 comments
ooblogger said...

Hello,

Please add your site at http://www.sweebs.com. Sweebs.com is a place where other people can find you among the best sites on the internet!
Its just started and we are collecting the best found on the net! We will be delighted to have you in the sweebs listings.

Regards
Kris

Sean Nieuwoudt said...

Nice one dude! thanks!

Sean
http://twitter.com/SeanNieuwoudt

Niju Mohan said...

Hey some js files are missing...

There is only php file in the download script

Anonymous said...

To Niju Mohan: this code does not require javascript at all, which is why it's so good. Pure PHP excellence!

Ncrow said...

hello i m jack here i just see u php tutorial ,upload and resize an image with php ,but i face a problem i using the script to upload a png
files format but after upload my files background is black colour. the oroginal files is transparency.how to make the png files still keep the transparency? thank you .

Anonymous said...

thanks

Anonymous said...

The jsquery does not download while downloading the script can you help it.....

Mike said...

Thanks, really helped me out! To set both a max width and height of 500 and 350 I added this:

$newwidthX=500;
$newheightX=($height/$width)*$newwidthX;
if($newheightX > 350) {
$newheight=350;
$newwidth=($newwidthX/$newheightX)*$newheight;
} else {
$newheight = $newheightX;
$newwidth = $newwidthX; }

Anonymous said...

Actually i am a java programmer. But now working in PHP. This article was very much useful for me..

very nice and simple..

Russell Harrower said...

Hi i need to know the following, what if two users have different photos with the same name?

Is there anyway to put the users ID number in front of the picture? Or rename the picture to there userid/pic.jpg?

Srinivas Tamada said...

@Russell Harrower

Registration time you have to create folder with the name of username in hosting area.

pic.jpg uploads into that particular folder.

eg: <?php echo $username ?>/pic.jpg

99% web projects no option for changing username

yusuf önaldı said...

good work, thanks for the code. I've just addapted it for our gallery on our site.

yusuf önaldı said...

hi again,
sometimes it's important to upload with a unique image name.

maybe you should add this part to your code for this;

i've changed this block;

$filename = "img/". $_FILES['file']['name'];

$filename1 = "img/small". $_FILES['file']['name'];

with this;

$image_name=time().'.'.$extension;

$filename = "img/". $image_name;

$filename1 = "img/small_". $image_name;

to upload images with a unique name via using time().

Srinivas Tamada said...

@yusuf önaldı


Nice : "to upload images with a unique name via using time()."

Thanks

Anonymous said...

First of all thanks!

I have a question!
When I upload png or gif with transparency it turns the transparency black. Do you know any solution to make it transparent again?

Anonymous said...

i want to display image from database..any idea?

Srinivas Tamada said...

Store image path in database table

Anonymous said...

Do you have any answer on how to get the transparency right in uploaded pictures?

If not just say it so I don't have to come back and look if you have answered.

Srinivas Tamada said...

PNG transparency issue.

I'm trying to solve this problem give some time.

ferdo said...

Hvala, ti, res dobra in enostavna skripta.

Tnx you, realy nice and easy script.

web said...

thanks for the script

Anonymous said...

where image create ?

i am not able to find created image

Alidad3250 said...

yes me too, i'm not able t find where they stored image...

Anonymous said...

<?php echo ("Testing can you use php in comments"); ?>

Anonymous said...

This is great! Thanks for this. 2 thumbs up!

Web Developer Bangladesh said...

thanks .. its help me too much today :)

Karl Kloppenborg said...

Awesome script, worked out of the box for me.. with a few minor changes I have it doing unique ident image names + store to MySQL, so it really fits what we are trying to achieve.

Cheers,
Karl. [K$]

Scotty said...

Why does this fail for large file sized images? For example, I can upload all the windows sample pictures which range in size from 27 KB to 103 KB. However, I can’t upload an image that is 1 MB such as this one http://tinyurl.com/yg4zfak

I believe it hangs up on the line $src = imagecreatefromjpeg($uploadedfile); (or png, gif).

How can I make it so this script will allow all sizes of images?
Thanks.

Srinivas Tamada said...

@Scotty

If you want to upload more than 1MB file, you have to increase the size value.

($size > MAX_SIZE*1024)

camille said...

thanks for the script! :)
question: what if i have multiple images? should i just create several input boxes? err.. help! :P

fsharing said...

your script so cool but i think beginners must modify this script a little bit simply by adding 'move_uploaded_file()' function and must create a directory name 'images'


kind regards and thanks for sharing!

Anonymous said...

excellent man, works good. thanks for the example

EL REY said...

nice script and as stated above this is alot for newbies if you could please help with how and where the changes could go am a learn as you go and am building my site from tutorials, so if you could please help as to where in page this goes so that the images could show I would really appreciate it my site is not up yet but am gonna place this code in the section so that visitor could post there pics of the party they have being and so! its gonna go on the section called subetusfotos.html Thanks Maria and Rey

Anonymous said...

hi. what about if i would like upload 2 or more photos? what to do? i`m new in php:/ help pls..
regards

Anonymous said...

very good stuff buddy !

Anonymous said...

to solve the png transparency
new width and heigt are ratios that i am working with
$temp=imagecreatetruecolor($newwidth,$newheight);

if($extension=="jpg" || $extension=="jpeg" ){
$img=imagecreatefromjpeg($upload);
imagecopyresampled($temp,$img, 0, 0, 0, 0,$newwidth,$newheight,$width,$height);
imagejpeg($temp,$path,100);
}
else if($extension=="png"){
$img=imagecreatefrompng($upload);
imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
imagepng($temp,$path);
}
else if($extension=="gif"){
$img=imagecreatefrompng($upload);
imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
imagepng($temp,$path,100);
}

FOX Creation said...

Nice one!
Only if you're file is to big, then he will also store it.. I build in a specification while it is exists or not and even a max height..

Thanks a lot dude!

".$filename1;

if(file_exists($filename)) {
$change='Het bestand '.$filenam.' bestaat al.';
$errors=1;
}
elseif(file_exists($filename1)){
$change='Het bestand '.$filenam.' bestaat al.';
$errors=1;
}
else{

$filename = stripslashes($_FILES['file']['name']);

$extension = getExtension($filename);
$extension = strtolower($extension);


if (($extension != "jpg"))
{

$change='Het plaatje dient een .jpg bestand te zijn ';
$errors=1;
}
else
{

$size=filesize($_FILES['file']['tmp_name']);


if ($size > MAX_SIZE*1024)
{
$change='You have exceeded the size limit! ';
$errors=1;
}
else{

if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['file']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);

}

echo $scr;

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


$newwidth=505;
$newheight=($height/$width)*$newwidth;
if($newheight>500){
$newheight=500;
$newwidth=($width/$height)*$newheight;
}
$tmp=imagecreatetruecolor($newwidth,$newheight);


$newwidth1=80;
$newheight1=($height/$width)*$newwidth1;
if($newheight1>95){
$newheight1=80;
$newwidth1=($width/$height)*$newheight1;
}
$tmp1=imagecreatetruecolor($newwidth1,$newheight1);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

imagecopyresampled($tmp1,$src,0,0,0,0,$newwidth1,$newheight1,$width,$height);


$filename = "schilderijen/". $_FILES['file']['name'];

$filename1 = "thumbs/th_". $_FILES['file']['name'];



imagejpeg($tmp,$filename,100);

imagejpeg($tmp1,$filename1,100);

imagedestroy($src);
imagedestroy($tmp);
imagedestroy($tmp1);
}}

}
}//Als bestandgrootte kleiner is dan 1 MB
}//als de bestanden nog niet bestonden.
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{

// mysql_query("update {$prefix}users set img='$big',img_small='$small' where user_id='$user'");
$change=' Image Uploaded Successfully!';
}

Anonymous said...

I have a better solution for the png transparency
else if($extension=="png"){
$img=imagecreatefrompng($upload);
//If our image have white background imagealphablending($temp,false);
//we capture the bg of our image $color=imagecolorallocatealpha($temp, 0, 0, 0, 127);
//fill the bg we capture before to put it in the resized one
imagefill($temp,0,0,$color);
//we restore the transparency(bg) imagesavealpha($temp,true);
//then we follow the steps of our friend =) imagecopyresampled($temp,$img,0,0,0,0,$newwidth,$newheight,$width,$height);
imagepng($temp,$p.'_m'.".".$extension); I hope it helps you :D
move_uploaded_file($upload,$p.".".$extension);

Mustafa said...

nice, i want to make an image resize but like (50x50, 20x20,...).
thanks..

Anonymous said...

Works great but I have a problem with gif extension. Uploaded gif images is black.
Output:
Warning: imagecreatefromgif() [function.imagecreatefromgif]: '/tmp/phpThbsBn' is not a valid GIF file in /home/rapidm/public_html/test/untitled.php on line 70

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/rapidm/public_html/test/untitled.php on line 79

Warning: imagedestroy(): supplied argument is not a valid Image resource in /home/rapidm/public_html/test/untitled.php on line 85

Help, anyone pls.
Thanks

NAGARAJ PATIL said...

Yeah! I got it finally...Thank u very much...I was facing a problem with resizing images since 2 days and your script helped me to complete my task..

John said...

Hi,

Thanks for the script. I just cant get it working though?

I have made a folder called images and one inside that called small.

Im testing it but nothing happens. IT just says its uploaded successfully except the images folder is empty.

Please help

Anonymous said...

yes me aswell - It says "uploaded successfully" but not an image being placed in the images folder on mine ftp.... me too I think is something wrong with what Im doing here?

Anonymous said...

Thanks man! I'm from Brazil!
I love the web too!!!

Anonymous said...

To get file extension just need a bit code :

$ext = substr(strrchr("hello.php", "."), 1);

Vasim Padhiyar

http://scriptforphp.blogspot.com

rentals said...

Dude, you rock. I got this working on the first try! Much love.

neto said...

How to add multiple images?

levani said...

What happens when an image already exist with the file name? As I see it's doesn't upload an image if another image is already uploaded with the same name... Is it possible to rename uploaded image if another image already exists?

Srinivas Tamada said...

@levani

Add Timestamp or Username to image file name.

eg: logo.png

to

eg : levanilogo.png or 1270723550logo.png

Jasper said...

Did someone already found a solution for the black .GIF output?

Thanks for the script b.t.w, it really helped me a lot!

Walkovik said...

@ John:

Remember to give permissions to folders, the file wont upload to the server if you dont give the right permissions.

@Srinivas

Thanks friend, you helped me a lot.

@ every reader

If you are using a form to store data in the server and in the database, you may be using an ID for each entry to the DB, just include the ID and that way you will be able to find who or which entry the image belongs to.

ric said...

works great, thanks!

webnet said...

there are missing some js files ?!
Or clear script code !

mayuri said...

hi
can u give me d code to add watermark to images?
thanks in advance

Mirko P said...

Bug:
$scr -> $src

Mirko

Mayuresh said...

Hi,

is that possible by any means that the image is resized at the client side without sending it to the server. Then it can be submitted.
It will be helpfull for slower connections.??

mitendra said...

Very nice script working fine on server but how to run this on local host?

Can anyone help me?

Team : Evilhackerz said...

can u post a new code for image upload using php,such that after upload we can have cropping and rename the image using random number.
plz help me ...

Anonymous said...

This is an awesome script. It's works very well and help me to finish my work faster.
Thank you

Mitendra Chaurasia said...

@ Anonymous, Is this script running on localhost. I want to work with this script for one project but it doesn't work on local but fine on server.

same problem with u?

tgreen8091 said...

Great Script! Thanks a bunch!

DWT said...

Great script! Thx for sharing it!

Anonymous said...

damn... nice...

Anonymous said...

hey....great code snippet..thanx for sharing :)

Anonymous said...

thanx for the code..but i have few questions:

1) where does the image created being stored?
2) how do you store the image links inside the database?

im kinda new for php..can someone fill me in please..

Anonymous said...

1) i tried the code..it shows no error but yet the produced image is not in the folder i specified

2) how can i save the produced image links inside the database?

Azarul said...

1) the code has no error..yet i cant seem to found the produced image..

2) how do i save the image links inside the database?

can someone please help me in this..really need your help..

Srinivas Tamada said...

@Azarul

Big Image :
$filename = "images/". $_FILES['file']['name'];

Small Image:
$filename1 = "images/small".$_FILES['file']['name'];

Images uploading in "images" folder

Eg: "abc.jpg" if you upload this file. It will upload to

images/adc.jpg
images/smallabc.jpg

So you have to store this path in database table

Azarul said...

sory for the 3 comments i post earlier..thought that my post wasnt coming up :(

@srinivas
i tried to create the images folder inside my htdocs..but the produced images arent there..can u help me figure out why this happen?

neha arora said...

well done....

Basit Nizami said...

thanks... works great... very simple...

took me not more than 30 seconds for it to be fully functional on my computer.

Regards,
Basit

munge83 said...

Hy, I just edit your code and make multi pic uploads
http://www.box.net/shared/2s3i7nsqch
I'm new in PHP programing, just learning, sorry if bad programing but it works like a charm ,
Thanks again

munge83 said...

Hy again, I edit it for second time, so I can esaly define how many uploads are,
in array just add a variable

http://www.box.net/shared/0jzcd8689s

$slike = array(file, flie1, fliel2, file3 ...)

but the hole file is acting funny , , sometimes , he uploads 3 images , sometimes 2 sometimes 1 , without errors ,
Help

munge83 said...

Looks like I'm fighting with my sellf.
Now its workig
Multi uploads

just add more variables in array $slike(file, file1, file2, file3 ......)

http://www.box.net/shared/tdf0zpaieu

Post a Comment

Orkut | FacebookAbout Me

Subscribe now!Feeds RSS

Subscribe now!Recent Posts

Subscribe now!Categories

Subscribe now!Comments

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Join into my community

Labs ProfileRelease

My ProfileTwitter