Compress Image Before Upload using PHP

A large size image takes more time to load a web page. If you want to load a large image without affecting the page load time, the image needs to be optimized to reduce the size. Image compression is very helpful to reduce the size of the image. In most cases, the user does not optimize the image when uploading through the website. It’s always a good idea to compress images and optimize the file size before uploading them to the server.

Compress and optimize image before upload can be easily implemented using PHP. In the image compress functionality, the file size is reduced before upload. The compressed image helps to reduce the uses of the server’s storage and load the web page faster. In this tutorial, we will show you how to compress image before upload using PHP.

File Upload Form

Create an HTML form with a file input field and a submit button. Make sure the <form> tag contains the following attributes.

  • method="post"
  • enctype="multipart/form-data"
<form action="upload.php" method="post" enctype="multipart/form-data">
    <label>Select Image File:</label>
    <input type="file" name="image">
    <input type="submit" name="submit" value="Upload">
</form>

After the form submission, the file data is submitted to the upload.php file for further processing.

Compress and Upload Image with PHP

The upload.php file handles the image compression and upload operations.

The compressImage() is a custom function that helps to compress and save image on the server using PHP. This function accepts the following parameters and returns the compressed image.

  • $source – An image file source to compress size.
  • $destination – Server path to save the compressed image.
  • $quality – Image quality.
<?php 
function compressImage($source$destination$quality) {
    
// Get image info
    
$imgInfo getimagesize($source);
    
$mime $imgInfo['mime'];
    
    
// Create a new image from file
    
switch($mime){
        case 
'image/jpeg':
            
$image imagecreatefromjpeg($source);
            break;
        case 
'image/png':
            
$image imagecreatefrompng($source);
            break;
        case 
'image/gif':
            
$image imagecreatefromgif($source);
            break;
        default:
            
$image imagecreatefromjpeg($source);
    }
    
    
// Save image
    
imagejpeg($image$destination$quality);
    
    
// Return compressed image
    
return $destination;
}

The convert_filesize() is a custom function that is used to convert file size in a human readable format. This function accepts the following parameters and returns the size in KB/MB/GB/TB/etc.

  • $bytes – File size in bytes
  • $decimals – Decimal places.
<?php 
function convert_filesize($bytes$decimals 2) {
    
$size = array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
    
$factor floor((strlen($bytes) - 1) / 3);
    return 
sprintf("%.{$decimals}f"$bytes pow(1024$factor)) . @$size[$factor];
}

When a file is submitted:

  • Retrieve the file info using the PHP $_FILES method.
  • Compress size and upload image using compressImage() function.
  • Get the optimized file size and convert it using convert_filesize() function using PHP.
<?php 
// File upload path
$uploadPath "uploads/";

$statusMsg '';
$status 'danger';

// If file upload form is submitted
if(isset($_POST["submit"])){
    
// Check whether user inputs are empty
    
if(!empty($_FILES["image"]["name"])) {
        
// File info
        
$fileName basename($_FILES["image"]["name"]);
        
$imageUploadPath $uploadPath $fileName;
        
$fileType pathinfo($imageUploadPathPATHINFO_EXTENSION);
        
        
// Allow certain file formats
        
$allowTypes = array('jpg','png','jpeg','gif');
        if(
in_array($fileType$allowTypes)){
            
// Image temp source and size
            
$imageTemp $_FILES["image"]["tmp_name"];
            
$imageSize convert_filesize($_FILES["image"]["size"]);
            
            
// Compress size and upload image
            
$compressedImage compressImage($imageTemp$imageUploadPath75);
            
            if(
$compressedImage){
                
$compressedImageSize filesize($compressedImage);
                
$compressedImageSize convert_filesize($compressedImageSize);
                
                
$status 'success';
                
$statusMsg "Image compressed successfully.";
            }else{
                
$statusMsg "Image compress failed!";
            }
        }else{
            
$statusMsg 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
        }
    }else{
        
$statusMsg 'Please select an image file to upload.';
    }
}

Display the uploaded image and optimized file size info.

<!-- Status message -->
<?php echo $statusMsg?>

<?php if(!empty($compressedImage)){ ?>
    <p><b>Original Image Size:</b> <?php echo $imageSize?></p>
    <p><b>Compressed Image Size:</b> <?php echo $compressedImageSize?></p>
    <img src="<?php echo $compressedImage?>"/>
<?php ?>

Preview and Rotate Image Before Upload using jQuery and PHP

Conclusion

Generally, the move_uploaded_file() function is used to upload file in PHP. But, if you want to compress the image before upload, our custom PHP function (compressImage()) is very useful. The example code helps you to compress the image file without using any compression library. With our compression script, you can compress different types of an image files (JPG, JPEG, PNG, and GIF).

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

2 Comments

  1. Yaser Riaz Said...
  2. Rahul Said...

Leave a reply

keyboard_double_arrow_up