Title: How to Compress Image Size in PHP Without Losing Quality — Complete Guide

👁️ 23 Views
|
📅 Jul 21, 2026
|
⏱️ 4 min read
Title:       How to Compress Image Size in PHP Without Losing Quality — Complete Guide

Every time a user uploads a large image to your server, it eats up storage space, slows down page load times, and increases your bandwidth costs — all without the user ever noticing the difference in quality. The good news is that PHP gives you powerful built-in tools to compress images automatically during the upload process, reducing file sizes by 60–80% while keeping the visual quality virtually identical to the original.

In this tutorial we will walk through exactly how to compress JPEG and PNG images in PHP without losing quality, how to overwrite or save the compressed version to a new path, and how to optionally delete the original uncompressed file from the server once the compressed copy is safely saved.

index.php 

Here we will create a html form, where we will upload images. Create a <Form> and put <input type="file"> and a submit button.

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="image" accept="images">
    <input type="submit" value="upload" name="submit">
</form>

 

index.php

Now, add few line of php code in same index.php or you can create another php file and import it to index page. First we will write code of uploading image in php. For this, create a folder name as uploaded, create this folder where your all files are available. 

 

if (isset($_POST['submit'])) {
    $image_name=$_FILES['image']['name'];
    $tmp_name=$_FILES['image']['tmp_name'];

    $directory_name='uploaded/';     //folder where image will upload
    $file_name=$directory_name.$image_name;
    move_uploaded_file($tmp_name, $file_name);

    $compress_file="compress_".$image_name;        
    $compressed_img=$directory_name.$compress_file;
    $compress_image=compressImage($file_name,$compressed_img);    
    unlink($file_name);            //delete original file
}

 

Now, we will create a function, name as  compressImage and put in below file upload code

function compressImage($source_image,$compress_image)
{
    $image_info=getimagesize($source_image);
    if ($image_info['mime']=='image/jpeg') {
        $source_image=imagecreatefromjpeg($source_image);
        imagejpeg($source_image,$compress_image,35);             //for jpeg or gif, it should be 0-100 
    }
    elseif ($image_info['mime']=='image/png') {
        $source_image=imagecreatefrompng($source_image);
        imagepng($source_image,$compress_image,3);                //for png it should be 0 to 9
    }
    return $compress_image;
}

Prefer a visual walkthrough? Watch the video below to see the complete PHP image compression implementation in action, step by step:

Subscribe to Our Newsletter

Join Our Developer Community!

Unsubscribe Anytime | No Spam