How to Compress Image size while Uploading with PHP

High-quality images take time to load on the webpage depending on the number of images.

You can create multiple sizes of the image file when uploading and use the low and high-quality images when required.

When reducing an image size then it also decreases its quality.

The best example of this is WordPress, whenever an image file is uploaded then it will generate a different-different size of the file. Those images will use in the theme according to requirement.

In this tutorial, I show how you can compress image size while uploading with PHP.

How to Compress Image size while Uploading with PHP


  1. HTML
  2. PHP
  3. Conclusion


Create a <input type='file'> element in <form> and submit button.

Completed Code

<form method='post' action='' enctype='multipart/form-data'>
  <input type='file' name='imagefile' >
  <input type='submit' value='Upload' name='upload'> 

2. PHP

Create a images directory to store image files.

Custom Function

Create a compressImage() function to compress JPEG, PNG, and GIF images.

The function takes 3 parameters –
1. Source
2. Destination
3. File quality

Call imagecreatefromjpeg($source), imagecreatefromgif($source), and imagecreatefrompng($source) to create a new image according to $info['mime'] value.

Execute imagejpeg() method to store image to the destination. Here, the third parameter quality is optional. It takes value from 0 – 100 and the default value is 75.

Form submit

Set location to images directory and check file extension. If it is valid then call compressImage() function where pass $_FILES['imagefile']['tmp_name'],$location, and 60.

Completed Code


  // Getting file name
  $filename = $_FILES['imagefile']['name'];
  // Valid extension
  $valid_ext = array('png','jpeg','jpg');

  // Location
  $location = "images/".$filename;

  // file extension
  $file_extension = pathinfo($location, PATHINFO_EXTENSION);
  $file_extension = strtolower($file_extension);

  // Check extension

    // Compress Image

    echo "Invalid file type.";

// Compress image
function compressImage($source, $destination, $quality) {

  $info = getimagesize($source);

  if ($info['mime'] == 'image/jpeg') 
    $image = imagecreatefromjpeg($source);

  elseif ($info['mime'] == 'image/gif') 
    $image = imagecreatefromgif($source);

  elseif ($info['mime'] == 'image/png') 
    $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);



3. Conclusion

In the example, I stored only the compressed image, not the original size image. You can store both the version of images while uploading.

Adjust the image quality when reducing size.

If you found this tutorial helpful then don't forget to share.