What is image compression

Image compression is a way to reduce size of the pictures (images) so that data is stored on the server in an efficient manner.

Steps to compress image

1. Create folder 'uploads' (or whatever name you give to your upload folder)

2. Create sub folder 'blogs' within 'uploads' folder (or whatever name you give to your sub folder)

3. Create a PHP form. Below mention coding contains complete code for image compression:

<?php
$img_error = '';
function fnc_image_compression($original_file, $compressed_file)
{
    $img_quality = 10; //100-> high quality 0-> low quality
    $info = getimagesize($original_file);
    if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($original_file);
    elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($original_file);
    elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($original_file);
    imagejpeg($image, $compressed_file, $img_quality);
    return $compressed_file;
}

if ($_POST) {
    if ($_FILES["file"]["error"] > 0) {
        $img_error = $_FILES["file"]["error"];
    } else if (
        ($_FILES["file"]["type"] == "image/png") ||
        ($_FILES["file"]["type"] == "image/gif") ||
        ($_FILES["file"]["type"] == "image/jpeg") ||
        ($_FILES["file"]["type"] == "image/pjpeg")
    ) {
        $target_dir = "uploads/blogs/"; //path to place the image
        $target_file = $target_dir . basename($_FILES["file"]["name"]);
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $newfile = 'actual_image_name' . '.' . $imageFileType;
        $newfilecomp = 'actual_image_name' . 'comp.' . $imageFileType;
        $filename = fnc_image_compression($_FILES["file"]["tmp_name"], $target_file);
        move_uploaded_file($filename, $target_dir);
        rename($filename, $target_dir . $newfilecomp);
        move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir . $newfile);
    } else {
        $img_error = "Uploaded image should be jpg or gif or png";
    }
} ?>
<html>
<head><title>Image Compression Tutorial</title></head>
<body>
<div class="err_message"> <?php if ($_POST) {
        if ($img_error) { ?> <label class="show_error"><?php echo $img_error; ?></label> <?php }
    } ?> </div>
<h1>Image Compression</h1>

<form action="" name="test_form" id="test_form" method="post" enctype="multipart/form-data">
    Browse Image: ----
    <input type="file" name="file" id="file"/>
    <br>
    <input type="submit" name="submit" id="submit" class="submit btn-success"/>
</form>
</body>
</html>

4. Run the file from the website.

5. Press 'Choose File' button

6. Browse the image file to be uploaded.

7. Press 'Submit' button.

By following the above steps, two copies of the image file is uploaded to the server. One is of the actual quality and the other is the compressed one. The later could be used on webpages and it would be uploaded within no time as it is very small in size.