Jump to content

Upload an image and downsize it (in KB`s) using php and GD

- - - - -

  • Please log in to reply
4 replies to this topic

#1
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
If you have a website where you let your users to upload images, you know that even the small images (around 100x100) can reach 50 - 100KB. This is way too much, when you could simply downsize the image to around 1 - 5KB, this is only the 1 - 5% of the size of the original image. Just imagine the benefits of downsizing 100.000 images...
Here you can find an example with an image before and after resizing: resize image using gd

So let`s begin downsizing those images...
The upload form
upload-form.php:
<form action="upload.php" method="POST" enctype="multipart/form-data">

<input type="hidden" name="MAX_FILE_SIZE" value="100000" />

Select image: <input name="theimage" type="file" /><br />

<input type="submit" value="Upload image" />

</form>
enctype="multipart/form-data" - this line tells the server that you want to send a file
MAX_FILE_SIZE - limits the maximum file size in bytes
type="file" - this is the file selecting input

Checking the image
First we need to check the file for 3 different problems:
- it was submitted or not ?
- it was uploaded ?
- it is too big ?
upload.php:
<?php

if(isset($_FILES['theimage'])){

   if($_FILES['theimage']['size'] < 1){

      echo 'Upload error!';

   }

   else if($_FILES['theimage']['size'] > 100000){

      echo 'The image is too big!';

   }

}

else {

   echo 'There is no image!';

}

?>
Check image type
Now we will check the type of the file, because we will accept only .jpg .gif and .png. At this step we will use some GD, too, because we will put our image in a variable:
<?php

if(isset($_FILES['theimage'])){

   if($_FILES['theimage']['size'] < 1){

      echo 'Upload error!';

   }

   else if($_FILES['theimage']['size'] > 100000){

      echo 'The image is too big!';

   }

   else {

      switch($_FILES['theimage']['type']){

         case 'image/gif':

         $image = imagecreatefromgif($_FILES['theimage']['tmp_name']);

         break;

         case 'image/jpeg':

         case 'image/pjpeg':

         $image = imagecreatefromjpeg($_FILES['theimage']['tmp_name']);

         break;

         case 'image/png':

         $image = imagecreatefrompng($_FILES['theimage']['tmp_name']);

         break;

      }

      if(!isset($image)){

         echo 'Only .gif, .jpg or .png images are allowed!';

      }

   }

}

else {

   echo 'There is no image!';

}

?>
Working with transparent images
We will downsize the images by converting it to .jpg. The jpg images can not be transparent and when the user uploads a transparent image, the transparent part will be painted in black. To make the transparent part white we need to create a white image with the same size as our uploaded image and then copy the uploaded image over the white image:
<?php

if(isset($_FILES['theimage'])){

   if($_FILES['theimage']['size'] < 1){

      echo 'Upload error!';

   }

   else if($_FILES['theimage']['size'] > 100000){

      echo 'The image is too big!';

   }

   else {

      switch($_FILES['theimage']['type']){

         case 'image/gif':

         $image = imagecreatefromgif($_FILES['theimage']['tmp_name']);

         break;

         case 'image/jpeg':

         case 'image/pjpeg':

         $image = imagecreatefromjpeg($_FILES['theimage']['tmp_name']);

         break;

         case 'image/png':

         $image = imagecreatefrompng($_FILES['theimage']['tmp_name']);

         break;

      }

      if(!isset($image)){

         echo 'Only .gif, .jpg or .png images are allowed!';

      }

      else {

         $size = getimagesize($_FILES['theimage']['tmp_name']);

         $background = imagecreatetruecolor($size[0],$size[1]);

         $white = imagecolorallocate($background,255,255,255);

         imagefill($background,0,0,$white);

         imagecopy($background,$image,0,0,0,0,$size[0],$size[1]);

      }

   }

}

else {

   echo 'There is no image!';

}

?>
Downsize the image
This is the final step, when we save the image in .jpg format:
<?php

if(isset($_FILES['theimage'])){

   if($_FILES['theimage']['size'] < 1){

      echo 'Upload error!';

   }

   else if($_FILES['theimage']['size'] > 100000){

      echo 'The image is too big!';

   }

   else {

      switch($_FILES['theimage']['type']){

         case 'image/gif':

         $image = imagecreatefromgif($_FILES['theimage']['tmp_name']);

         break;

         case 'image/jpeg':

         case 'image/pjpeg':

         $image = imagecreatefromjpeg($_FILES['theimage']['tmp_name']);

         break;

         case 'image/png':

         $image = imagecreatefrompng($_FILES['theimage']['tmp_name']);

         break;

      }

      if(!isset($image)){

         echo 'Only .gif, .jpg or .png images are allowed!';

      }

      else {

         $size = getimagesize($_FILES['theimage']['tmp_name']);

         $background = imagecreatetruecolor($size[0],$size[1]);

         $white = imagecolorallocate($background,255,255,255);

         imagefill($background,0,0,$white);

         imagecopy($background,$image,0,0,0,0,$size[0],$size[1]);

         $image = $background;

         $filename = explode(".",$_FILES['theimage']['name']);

         $filename = $filename[0];

         imagejpeg($image,$_SERVER['DOCUMENT_ROOT'] . '/thumbnails/' . $filename . '.jpg',90);

         imagedestroy($image);

         echo 'Your image: <img src="/thumbnails/' . $filename . '.jpg" />';

      }

   }

}

else {

   echo 'There is no image!';

}

?>
If you have any questions please don`t hesitate to ASK!
Btw here is the original tutorial: upload and downsize image with php and gd

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
  • Location:Vancouver, Eh! Cleverness: 200
Ah, thank you for your tutorial submission. It is quite informative to people who just take images as they are.

I would note images with less than 16 colours can remain extremely small even at massive sizes if they are in .png format. Handling that would be left to the reader as an exercise!
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
What would happen if my image name had two periods in it's name? For example: my.image.jpg
Relying on explode() and the zeroth index might not be the best idea.

#4
Csabi

Csabi

    Learning Programmer

  • Members
  • PipPipPip
  • 62 posts
I`we used that only as an example...

#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
  • Location:New York, NY
Just because it is an example, doesn't excuse it from being full of bugs and insecure...

By writing code and publishing it as a tutorial or example, you are teaching people. Thus, if your code is full of bugs and security vulnerabilities, you are teaching people how to write code full of bugs and security vulnerabilities - a habit that should be avoided.

         $filename = explode(".",$_FILES['theimage']['name']); 

         $filename = $filename[0]; 

         imagejpeg($image,$_SERVER['DOCUMENT_ROOT'] . '/thumbnails/' . $filename . '.jpg',90); 
If my image name was my.image.jpg $filename would then become my.jpg because you are using the zeroth element returned by explode, a result that could have potential drawbacks. The proper alternative would be to use pathinfo() which will return the file name without the extension.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users