Compress Image Before Upload using PHP

Compress Image Before Upload using PHP

Large image size always takes time to load a web page. We always need to upload compress images to the server, If you want to load a large image without affecting the page load time, then the images on the page need to be optimized. When we make the web application we always have to make sure that the images should be well compressed so that it does not affect the website speed.

Image size plays a very important role in any web application. There many image compression website where you can compress the image and then upload to the server, and other than that there are many libraries or built-in functions which reduces the size of the image.

What is image copression?

Image compression is a type of data compression that reduces the size of the image. Nowadays almost all websites use image compression to reduce the website page load.

The best example of this is WordPress, whenever an image file is uploaded then it will generate the different-different size of the file. Those images will use in the theme according to requirement. If you will check, all the CMS compresses the image before uploading them on the server.

Why we need a compressed image on the website?

Nowadays we can see that the website loading speed plays a very important role. According to google many websites that have reduced their website load time have observed increased daily visitors and many companies website having more load time loses most of the online customoer.,Because nowadays no one wants to wait or stuck on a particular point for some time. That’s why in order to make good user experience it is a must to keep the website page size minimum as much possible as can.

Image compression is also one of the ways by which we can reduce the website load time and server utilization. That’s why we should compress all the images before storing them on the server.

In how many ways we can compress the image size for the website?

Images uploading are very important and it should be compressed as much as possible. You can write a PHP code that reduces or compress image size while uploading it to the server. there are multiple ways you can use to reduce or compress the image size.

  • Using 3rd party libraries
  • Using Internal functions
  • Using an online compression tool

It is a must to reduce the image size which is going to upload on the website. We have already mentioned the way by which you can reduce or compress the image size. In this tutorial, we will tell you how you can compress or reduce the image size using PHP code.

File Upload Form

Let’s create Create an HTML form with a file input field and a submit button.

<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 above code snippet allows users to choose the image file to the website or server. On click submit button the file data is submitted to the upload.php file for further checks and upload.

Compress and Upload Image with PHP Before upload

upload.php file handles the image compression and uploads operations. compressImage() is a custom function that reduces the size and upload the image to the server using PHP.

<?php 
 
 
function compressImage($source, $destination, $quality) { 
    $imgInfo = getimagesize($source); 
    $dataMine = $imgInfo['mime']; 
     
    switch($dataMine){ 
        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); 
     
    // final Return compressed image 
    return $destination; 
} 
 
 
// File upload path in the directory 
$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."; 
            }else{ 
                $statusMsg = "Image compress failed!. Try again"; 
            } 
        }else{ 
            $statusMsg = 'only JPG, JPEG, PNG, & GIF files are allowed to upload. Try again'; 
        } 
    }else{ 
        $statusMsg = 'Please select an image file to upload.'; 
    } 
} 
 
// Display status
echo $statusMsg; 
 
?>

Conclusion

Mostly we use move_uploaded_file() function to upload the file to the server. But in this tutorial, you can use our custom made compressImage() function to reduce the image size. You can invoke this function in any PHP file to upload the script without interrupting the other functionality. With the above code, you can compress JPG, JPEG, PNG, and GIF image files.

You can also check How to enable gzip compression in cPanel

Spread the love