Compress Image Before Upload using PHP

The large size image takes more time to load a web page. If you want to load a large image without affecting the page load time, the image needs to be optimized to reduce the size. Image compression is very helpful to reduce the size of the image. Generally, the user does not optimize the image when uploading through the website. In this case, compress image before upload to optimize the image.

Compress/optimize image before upload can be easily implemented using PHP. In the image compress functionality, the file size is reduced before upload. The compressed image helps to reduce the uses of the server’s storage and load the web page faster. In this tutorial, we will show you how to compress image before upload using PHP.

File Upload Form

Create an HTML form with a file input field and a submit button. Make sure the <form> tag contains the following attributes.

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

After the form submission, the file data is submitted to the upload.php file for further processing.

Compress and Upload Image with PHP

In the upload.php file handles the image compression and upload operations.

  • compressImage() is a custom function that helps to compress and save image on the server using PHP.
  • If the file is submitted,
    • Retrieve the file info using the PHP $_FILES method.
    • Compress size and upload image using compressImage() function.
    • Render the image upload status.

 * 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
$image imagecreatefromjpeg($source);
$image imagecreatefrompng($source);
$image imagecreatefromgif($source);
$image imagecreatefromjpeg($source);
// Save image
// Return compressed image
return $destination;

// File upload path
$uploadPath "uploads/";

// If file upload form is submitted
$status $statusMsg '';
$status 'error';
$_FILES["image"]["name"])) {
// File info
$fileName basename($_FILES["image"]["name"]);
$imageUploadPath $uploadPath $fileName;
$fileType pathinfo($imageUploadPathPATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif');
// Image temp source
$imageTemp $_FILES["image"]["tmp_name"];
// Compress size and upload image
$compressedImage compressImage($imageTemp$imageUploadPath75);
$status 'success';
$statusMsg "Image compressed successfully.";
$statusMsg "Image compress failed!";
$statusMsg 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
$statusMsg 'Please select an image file to upload.';

// Display status message
echo $statusMsg;


Related Articles

Comments 0