Reduce Image File Size While Uploading It Using PHP Code

It is a very common process to upload images dynamically to the server or website by the users and admins. However, while we upload the image with a large file size on the website, it is likely to take more time to load and effects website ranking. So the developer should write the code to reduce the image file size as much as possible while uploading to the website. Using PHP code, we can easily reduce the file size of those uploaded images during the time of upload.

Code to reduce the file size of an image:

function compress_image($source_file, $destination_file, $quality) {
    $info = getimagesize($source_file);
    if(!empty($info)) {
        switch($info['mime']) {
            case 'image/jpeg' :
                // set quality
                if($quality == '' || $quality < 0 || $quality > 100) $quality = 80; 
 
                // create a new image from the file
                $image = imagecreatefromjpeg($source_file);
                imagejpeg($image, $destination_file, $quality);
                return $destination_file;
                break;

            case 'image/png' :
                // set quality
                if($quality == '' || $quality < 0 || $quality > 9) $quality = 6;

                // create a new image from the file
                $image = imagecreatefrompng($source_file);
                imagepng($image, $destination_file, $quality);
                return $destination_file;
                break;

            case 'image/gif' :
                // set quality
                if($quality == '' || $quality < 0 || $quality > 100) $quality = 70;

                // create a new image from the file
                $image = imagecreatefromgif($source_file);
                imagegif($image, $destination_file, $quality);
                return $destination_file;
                break;
        }
    }
}
$ci = compress_image($source_image, $destination_image, 90);

In the above PHP function, we pass the source image ( i.e., $source_image ), destination image ( $destination_image ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source_file);

The getimagesize() function is used to find the size of the given image and return the dimensions along with the file type.

Example:

$info = getimagesize($source_file);
print_r($info);

Output:

Array ( [0] => 1080 [1] => 765 [2] => 2 [3] => width="1080" height="765" [bits] => 8 [channels] => 3 [mime] => image/jpeg )
$image = imagecreatefromjpeg($source_file);
$image = imagecreatefromgif($source_file);
$image = imagecreatefrompng($source_file);

All the above PHP functions are used to create a new image from the given file. These functions are used to return an image identifier representing the image obtained from the given filename.

imagejpeg($image, $destination_file, $quality);
imagepng($image, $destination_file, $quality);
imagegif($image, $destination_file, $quality);

All the above PHP functions are used to create a JPEG / PNG / GIF file from the given image.

Syntax:

imagejpeg ( $source_image, $destination_image, $quality )
imagepng ( $source_image, $destination_image, $quality )
imagegif ( $source_image, $destination_image, $quality )

In the above PHP functions, $quality is optional and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default range is 75.

Complete code to reduce the image file size:

<?php
    $name = ''; $type = ''; $size = ''; $error = '';
 
    function compress_image($source_file, $destination_file, $quality) {
        $info = getimagesize($source_file);
        if(!empty($info)) {
            switch($info['mime']) {
                case 'image/jpeg' :
                    // set quality
                    if($quality == '' || $quality < 0 || $quality > 100) $quality = 80;

                    // create a new image from the file
                    $image = imagecreatefromjpeg($source_file);
                    imagejpeg($image, $destination_file, $quality);
                    return $destination_file;
                    break;

                case 'image/png' :
                    // set quality
                    if($quality == '' || $quality < 0 || $quality > 9) $quality = 6;

                    // create a new image from the file
                    $image = imagecreatefrompng($source_file);
                    imagepng($image, $destination_file, $quality);
                    return $destination_file;
                    break;

                case 'image/gif' :
                    // set quality
                    if($quality == '' || $quality < 0 || $quality > 100) $quality = 70;

                    // create a new image from the file
                    $image = imagecreatefromgif($source_file);
                    imagegif($image, $destination_file, $quality);
                    return $destination_file;
                    break;
            }
        }
    }

    if ($_POST) {
        if ($_FILES["file"]["error"] > 0) {
            $error = $_FILES["file"]["error"];
        }
        else if (($_FILES["file"]["type"] == "image/gif") || 
                 ($_FILES["file"]["type"] == "image/jpeg") ||
                 ($_FILES["file"]["type"] == "image/png")) {

            switch($_FILES["file"]["type"]) {
                case 'image/jpeg' :
                     $url = 'destination.jpg';
                     break;

                case 'image/png' :
                     $url = 'destination.png';
                     break;

                case 'image/gif' :
                     $url = 'destination.gif';
                     break;
            }
            $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);

            $buffer = file_get_contents($url);
            /* Force download dialog... */
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");

            /* Don't allow caching... */
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

            /* Set data type, size and filename */
            header("Content-Type: application/octet-stream");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: " . strlen($buffer));
            header("Content-Disposition: attachment; filename=$filename");

            /* Send our file... */
            echo $buffer;
        }else {
            $error = "Uploaded image should be jpg or gif or png";
        }
    }
?>
<html>
    <head>
        <title>Php code to compress the image file size</title>
    </head>

    <body>
        <div class="message">
        <?php
            if($_POST){
                if ($error) {
                ?>
                    <label class="error"><?php echo $error; ?></label>
                <?php
                }
            }
        ?>
        </div>

        <fieldset>
            <legend>Upload Image:</legend>
            <form action="" name="upload-form" id="upload-form" method="post" enctype="multipart/form-data">
                <ul>
                    <li>
                        <label>Upload:</label>
                        <input type="file" name="file" id="file"/>
                    </li>
                    <li>
                        <input type="submit" name="submit" id="submit" class="submit"/>
                    </li>
                </ul>
            </form>
        </fieldset>
    </body>
</html>

Note: Ensure the server support the GD library. Because the GD library is very important to run all the image creation function in PHP.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *