php compress image before upload – How to Compress Image size while Uploading with PHP?

php compress image before upload : By using PHP inbuilt functions we can do it very easily. PHP allows you to easily implement compress / optimize image before upload.

php compress image before upload

Compress Image size while Uploading in PHP : In this post we will learn how to compress image size before upload on a server. Also The file size is reduced before uploading when compressing the image.

Reduce Image Size Before Upload Using PHP

Step-1: Create Image Upload Form

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

Step-2: Compress and Upload Image with PHP


function freeToFlexDp($source, $savePath, $dpQty) { 
    $imgInfo = getimagesize($source); 
    $mime = $imgInfo['mime']; 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($source); 
           imagejpeg($image, $savePath, $dpQty);
        case 'image/png': 
            $image = imagecreatefrompng($source); 
            imagepng($image, $savePath, $dpQty);
        case 'image/gif': 
            $image = imagecreatefromgif($source); 
            imagegif($image, $savePath, $dpQty);
            $image = imagecreatefromjpeg($source); 
           imagejpeg($image, $savePath, $dpQty);
    return $savePath; 
$uploadPath = "media/"; 
$status = $displayEventMessage = ''; 
    $status = 'error'; 
    if(!empty($_FILES["image"]["name"])) { 
        $fileName = basename($_FILES["image"]["name"]); 
        $profileImgUpload = $uploadPath . $fileName; 
        $fileType = pathinfo($profileImgUpload, PATHINFO_EXTENSION); 
        $allowTypes = array('jpg','png','jpeg','gif'); 
        if(in_array($fileType, $allowTypes)){ 
            $imageTemp = $_FILES["image"]["tmp_name"]; 
            $outputs = freeToFlexDp($imageTemp, $profileImgUpload, 75); 
                $status = 'success'; 
                $displayEventMessage = "Profile DP compressed successfully."; 
                $displayEventMessage = "Profile DP compress failed!"; 
            $displayEventMessage = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.'; 
        $displayEventMessage = 'Please select an image file to upload.'; 
echo $displayEventMessage; 

Free Live Chat for Any Issue

Don’t Miss : How to compress image size while uploading in PHP?

I hope you get an idea about php compress image before upload.
I would like to have feedback on my
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.