A Complete Tutorial to Compress Image before upload using PHP

An image adds the breathe to your website content. The faster loading image can improve the user experience and retention on your web. To make the image load faster, you need to compress image before upload using PHP. This is what we call image optimization. 

A well compressed image with reduced file size occupies less space on the server. This in turn improves the website loading time. Further, in this article, we will learn how to compress website images using PHP

Create Upload form

Firstly, you need to create an HTML form with an input field and submit button. Your <form> tag must contain the following code. 

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

Once the form is submitted, the file data gets submitted to the upload.php for advanced processing. 

Compress image before upload using PHP

<?php 
 
/* 
 * Custom function to compress image size and 
 * upload to the server using 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; 
} 
 
 
// File upload path 
$uploadPath = "uploads/"; 
 
// If file upload form is submitted 
$status = $statusMsg = ''; 
if(isset($_POST["submit"])){ 
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        // File info 
        $fileName = basename($_FILES["image"]["name"]); 
        $imageUploadPath = $uploadPath . $fileName; 
        $fileType = pathinfo($imageUploadPath, PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            // Image temp source 
            $imageTemp = $_FILES["image"]["tmp_name"]; 
             
            // Compress size and upload image 
            $compressedImage = compressImage($imageTemp, $imageUploadPath, 75); 
             
            if($compressedImage){ 
                $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 status message 
echo $statusMsg; 
 
?>

Conclusion

Image compression will enhance your website experience. It will help in providing the content with images in faster time durations. Ultimately, your website user experience will improve. Moreover, the user time span will increase as the quality information will get provided in short time. 

So, this example code will help you to  compress image before upload using PHP. You can compress various image formats like JPG, PNG, GIF, JPEG, etc using this custom function code named (compressImage()).

Also Read: How to upload multiple files with form data using jQuery, Ajax, and PHP

How to add datatable custom filter dropdown server-side processing with PHP