How to Compress Image Size Without Losing Quality in PHP

PHP provides features to resize, compress images without losing the quality of it.

PHP has default functions to compress images and to resize them. we can use this default function to convert thumbnail image and compress it without losing quality of image.

Create a form in an HTML/PHP file

<!DOCTYPE html>
<html>

<head>
    <title>How to compress an image without losing quality in PHP</title>
</head>

<body>
    <form action='' method='POST' enctype='multipart/form-data'>
        <input name="files" type="file" accept="image/*">
        <button type="submit">SUBMIT</button>
    </form>
</body>

</html>

Note: enctype=”multipart/form-data” is compulsory for image upload process via post method in form.

Add  PHP code at the top of PHP file

<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
    $file_name = $_FILES["files"]["name"];
    $file_type = $_FILES["files"]["type"];
    $temp_name = $_FILES["files"]["tmp_name"];
    $file_size = $_FILES["files"]["size"];
    $error = $_FILES["files"]["error"];
    if (!$temp_name)
    {
        echo "ERROR: Please browse for file before uploading";
        exit();
    }
    function compress_image($source, $destination, $quality)
    {
        $info = getimagesize($source_url);
        if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($source);
        elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($source);
        elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($source);
        imagejpeg($image, $destination_url, $quality);
        echo "Image uploaded successfully.";
    }
    if ($error > 0)
    {
        echo $error;
    }
    else if (($file_type == "image/gif") || ($file_type == "image/jpeg") || ($file_type == "image/png") || ($file_type == "image/pjpeg"))
    {
        $filename = compress_image($temp_name, "uploads/" . $file_name, 80);
    }
    else
    {
        echo "Uploaded image should be jpg or gif or png.";
    }
} ?>

Explanation

Checked for the form request method. For File and Image upload POST method is compulsory.

After that, we defined some variables related to the uploaded file. Like, File Name , File Type , File Size , Temporary Location of Uploaded File , and Error in File Upload Process if any.

Next, we created a compress_image() function to upload and compress the image. In this function, we passed three variables of the uploaded file.

  1. $source: It is the temporary location in our case of file upload.
  2. $destination It is the destination path where we want to upload our Image.
  3. $quality: It is the rate of Image quality we want to maintain from 1 to 100. If we want to maintain 100% quality we can simply apply 100 or we can pass 80 if we want to compress and lose the image quality by 20%.

In the n function we first found for image specifications by using getimagesize() function and checked for its mime type.

From mime type, we checked the image is valid or not and create a related replica of image in PHP according to jpeg, png, gif using imagecreatefromjpeg()imagecreatefrompng()imagecreatefromgif() respectively and saved it in $image variable.

Finally, we created a jpeg image with the help of a $image variable by using imagejpeg() function.

imagejpeg() function is basically image creator function from raw image data. There are three arguments we passed in imagejpeg() function.

  1. $image: Raw image data we created and stored in $image variable
  2. $destination: Destination Folder/Directory path where we want to create a new image
  3. $quality: The rate of image quality we want to maintain

In the end, we checked for error in the upload process and used our compress_image() function to handle compression of the uploaded image.

 

Posted in PHP

Leave a Reply

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