Compress Image Size in PHP Without Losing Quality

If you are searching for a script to compress image size in PHP without losing quality, you have found the best tutorials. Here, You will get the standard source code to implement in your project.

If you upload a large size image in your application, it will take more time to load the web page. It is not good for any web application. So, You must reduce the image size before upload.

compress image size using php

How to Compress Image in PHP

First of all, Read the following algorithm to easily compress images in PHP. It will make it easy to learn.

  • Create a file input field within a form to select an image from your computer.
  • Even create a submit input button within the form to upload images to the server.
  • If the submit input button is set, call a custom function to execute the image upload script.
  • If the allowed image type is valid, call another custom function to compress the image size. This function will reduce image size using PHP imagejpeg() then upload it to the server.

Read Also

How to Upload File Using PHP

Now, create a folder structure to write the following PHP script.

myproject
   |__uploads/
   |__upload-form.php
   |__compress-script.php
   |

1. Create an HTML Form to Upload Image

  • Start the session at the top & get a file uploading message through the session $_SESSION['msg'].
  • First, Print session value to display error or success uploading message then unset session variable.
  • Create an HTML form to submit Youtube Video URL. This form must have the following attributes
  • method="post" – It will send the input URL with security
  • enctype= "multipart/form-data" – Used to allow different types of images.
  • action="compress-script.php" – It will redirect to a compressed image after submitting the form

File Name – upload-form.php

<?php

session_start();
$msg= !empty($_SESSION['msg'])? $_SESSION['msg']:'';
?>

<!DOCTYPE html>
<html>
<head>
  <title>Compress Image Size Using PHP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<!--====image upload form===-->
    
<?php

 echo $msg;
 unset($_SESSION['msg']);
?>

<form action="compress-script.php" method="post" enctype="multipart/form-data">
     <label>Select Your File</label>
    <input type="file" name="image">
    <input type="submit" value="Compress Now" name="submit">
</form>

<!-- image upload form====-->
</body>
</html>

 

2. Compress image Size Using PHP

You can use the following two custom functions. These functions will easily reduce image size then upload it to the server.

  • upload_image() – It will upload the image to the server if the selected image type will be allowed.
  • compress_image – It will compress image size without losing quality and save it to the server. This function will be  within upload_image()  function.

File Name – compress-script.php

<?php

// uploading files on submit
if(isset($_POST['submit'])){ 
  
    //  uploading files
    $msg= upload_image(); 
    session_start();
    $_SESSION['msg']= $msg;
    header('location:upload-form.php');

}


function upload_image(){

    $uploadTo = "uploads/"; 
    $allowImageExt = array('jpg','png','jpeg','gif');
    $imageName = $_FILES['image']['name'];
    $tempPath=$_FILES["image"]["tmp_name"];
    $imageQuality= 60;

    $basename = basename($imageName);
    $originalPath = $uploadTo.$basename; 
    $imageExt = pathinfo($originalPath, PATHINFO_EXTENSION); 

    if(empty($imageName)){ 
       $error="Please Select files..";
       return $error;
     
     }else{
   
    if(in_array($imageExt, $allowImageExt)){ 

  $compressedImage = compress_image($tempPath, $originalPath, $imageQuality);
    if($compressedImage){
     return "Image was compressed and uploaded to server";
    }
    else{
     return "Some error !.. check your script";
    }
   }else{
     return "Image Type not allowed";
   }

} 
}

function compress_image($tempPath, $originalPath, $imageQuality){
  
    // Get image info 
    $imgInfo = getimagesize($tempPath); 
    $mime = $imgInfo['mime']; 
     
    // Create a new image from file 
    switch($mime){ 
        case 'image/jpeg': 
            $image = imagecreatefromjpeg($tempPath); 
            break; 
        case 'image/png': 
            $image = imagecreatefrompng($tempPath); 
            break; 
        case 'image/gif': 
            $image = imagecreatefromgif($tempPath); 
            break; 
        default: 
            $image = imagecreatefromjpeg($tempPath); 
    } 
     
    // Save image 
    imagejpeg($image, $originalPath, $quality);    
    // Return compressed image 
    return $originalPath; 

}
?>

 

In this code, by default image quality is set $imageQuality= 60 you can change its value from 60 to any other value according to your requirement.

After Implementing this code, open the file upload form and select an image from your computer. then click submit button. After that, you have to wait for a few seconds then the image will be compressed automatically with original image quality.

If you want to create an image compression website then this code will be most useful. So, you should integrate this code into your website.

 

My Suggestion

I have shared the best way to compress image size using PHP. Now, you can easily implement it with different type types of images like jpg, png, gif.

If you like this tutorial, share it with your friend as well. Even you can put your query into the below comment box. You can continue to visit my site for getting a new concept in PHP coding.

 

 

Categories PHP

Leave a Comment