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


Contents

  1. HTML
  2. PHP
  3. Conclusion

1. HTML

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'> 
</form>

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

<?php
if(isset($_POST['upload'])){

  // 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
  if(in_array($file_extension,$valid_ext)){

    // Compress Image
    compressImage($_FILES['imagefile']['tmp_name'],$location,60);

  }else{
    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.

30 thoughts on “How to Compress Image size while Uploading with PHP”

  1. Is it compressing an image before uploading file? I want to know this because we have limited bandwidth on vessel. I need some solution, which compress images and saves the traffic.

    Reply
  2. Thank you so much, Yogesh! Exactly what I was looking for and easier than expected! Bookmarked! I just wish, it could compress the image without loosing quality for the web.

    Reply
  3. Is there any way to specify the size of file to be uploaded.
    Like I want the uploaded file to be of 500kb only no matter whatever be the size

    Reply
  4. You just made my day, sir. I am developing a music sharing site with chat capability and posts which includes images and videos. I must give you credits on my project. I will notify you when it’s done. Hope to go live in October. Thanks
    Ps. I used the compressImage() for my image uploads, can I modify it to compress videos and audio?

    Reply
  5. Just have to give you a huge thank you! Now users can upload 8mb PNG images and it gets down to 300kb without losing too much quality. Much appreciated, thanks!

    Reply

  6. Fatal error: Uncaught Error: Call to undefined function imagecreatefromjpeg() in C:\xampp\htdocs\clients\index.php:40 Stack trace: #0 C:\xampp\htdocs\clients\index.php(27): compressImage(‘C:\\xampp\\tmp\\ph…’, ‘images/20201227…’, 60) #1 {main} thrown in C:\xampp\htdocs\clients\index.php on line 40″
    am getting that error some functions are undefined

    Reply
  7. A big thank you for this code and these clear explanations.

    Could we add a rule to reduce the size of the images while keeping the height to width ratio?

    Example:

    I have a 4000×4000 image of 4 mega

    With your example we reduce the weight of the images so that the image reaches 2 mega.

    If we add a rule to divide the dimension in 2000×2000 before going into the code to reduce, we should be able to reduce the weight even more?

    Is it possible?

    Thanks a lot for your help.

    Reply
  8. I’m developing a WordPress plugin. Have tried using this code a lot, no response. Do we need to add a DB connection as well? Or can it run without it. Also, I replaced this code with the basic code of file upload in PhP. Am I doing it right? Please reply.

    Thank you!

    Reply

Leave a Comment