Compress Image Before Upload using PHP

Compress Image Before Upload using PHP

  • PHP
  • 4 mins read

A web page with a large image will take longer to load. In order to avoid slowing down the page load time, large images must be optimized to reduce their file size. Compressing an image is an effective method for decreasing its file size. When users upload photos to a website, they rarely give the file the attention it needs to look its best. Before putting images on a server, it's always a good idea to reduce their size through compression and optimization.

PHP makes it simple to add functionality that compresses and optimizes images before they are uploaded. To facilitate uploading, the image size can be decreased using the compress feature. The image compression results in less data being stored on the server, which in turn speeds up page loads. In this tutorial, we will show you how to compress image before upload using PHP.

Create File Upload Form

Making a simple HTML form with a file upload field and a submit button is easy. Make sure the following attributes are present in the <form> tag:

  • 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>

The upload.php file receives the uploaded file and its data after the form is submitted.

Compress and Upload Image with PHP

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

In order to save space on the server, PHP offers a specialized function called compressImage(). The compressed image is returned after the following parameters are supplied to the function.

  • $source – A size-reduction image file source.
  • $destination – Compressed image server save location.
  • $quality – Image quality.
<?php 
function compressImage($source, $destination, $quality) { 
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime']; 
     
    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); 
    } 
     
    imagejpeg($image, $destination, $quality); 
     
    return $destination; 
}

The change_filesize() function is a user-defined helper for converting between binary and human-readable file sizes. The following values are accepted by this function, and the size will be returned in bytes.

  • $bytes – File size in bytes
  • $decimals – Decimal places.
<?php 
function change_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:

  • In PHP, this is done with the $_FILES method.
  • Upload images with reduced file sizes by calling the compressImage() function.
  • If you're using PHP, you can use the change_filesize() function to get the compressed file size and then convert it.
<?php 
$uploadPath = "uploads/"; 
 
$statusMsg = ''; 
$status = 'danger'; 
 
if(isset($_POST["submit"])){ 
    if(!empty($_FILES["image"]["name"])) { 
        $fileName = basename($_FILES["image"]["name"]); 
        $imageUploadPath = $uploadPath . $fileName; 
        $fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION); 
         
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $imageTemp = $_FILES["image"]["tmp_name"]; 
            $imageSize = convert_filesize($_FILES["image"]["size"]); 
             
            $compressedImage = compressImage($imageTemp, $imageUploadPath, 75); 
             
            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.

<?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 } ?>

Summary

In most cases, the move_uploaded_file() function is used to upload files in PHP. However, our specialized PHP function (compressImage()) comes in handy if you wish to compress the image prior to upload. The provided code snippet illustrates how to achieve the desired results without resorting to a third-party compression library. To compress various image formats, use the script we've developed (JPG, JPEG, PNG, and GIF).