How to Reduce Image File Size While Uploading Using PHP

Last updated 1 month ago | 49 views 75     5

Tags:- PHP

Reducing image file size during the upload process is crucial for enhancing website performance and user experience. Large image files can slow down page load times and consume more server resources. By compressing images during the upload process, you can maintain visual quality while reducing file size.

✅ Step 1: Handle the Image Upload

The first step is to handle the image file that is being uploaded via an HTML form. The PHP script will capture the uploaded file and pass it to the compression function.

if(isset($_FILES['image'])) {
    $image = $_FILES['image']['tmp_name'];
    $destination = 'uploads/compressed_image.jpg';
    compressImage($image, $destination, 75);
}
  • $_FILES['image']: Captures the uploaded file.

  • $image: Temporary file path.

  • $destination: Path where the compressed image will be saved.

  • compressImage(): A custom function to handle compression.

✅ Step 2: Create the Compression Function

The compressImage function handles the actual compression. It checks the file type and applies the appropriate compression method.

function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
        imagejpeg($image, $destination, $quality);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
        imagepng($image, $destination, floor($quality / 10)); // PNG quality is between 0-9
    }
}
  • getimagesize(): Retrieves the MIME type of the image.

  • imagecreatefromjpeg() and imagecreatefrompng(): Create image resources from the original file.

  • imagejpeg() and imagepng(): Save the compressed image with the specified quality.

✅ Step 3: HTML Form for Upload

The HTML form allows users to select and upload an image.

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="image" accept="image/*">
    <button type="submit">Upload and Compress</button>
</form>
  • enctype="multipart/form-data": Required for file uploads.

  • accept="image/*": Limits the file selection to images.

✅ Step 4: Set Proper Permissions

Ensure that the uploads directory is writable. You can change the permissions via the command line:

chmod 777 uploads

This step is essential to allow PHP to save the compressed image.

Conclusion

By implementing this approach, you can efficiently reduce image file size while preserving visual quality. This method improves page load times, reduces bandwidth usage, and enhances the overall user experience.