Compress Image size while Uploading in PHP

Generic placeholder image
Brijpal Sharma
php  

Date:-May 27th, 2019 , Posted On:- Web Development


In this tutorial, we are going to learn about how to compress image size while uploading with PHP

First, create a new table

Step 1:- Create a compress_image table in the database.

CREATE TABLE `codingmantra`.`compress_image` ( `id` INT(11) NOT NULL AUTO_INCREMENT , `image` VARCHAR(250) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;

Step 2:- Create a connection to the database in the PHP file.

The mysqli_connect() function opens a new connection to the MySQL server.

Syntax : - mysqli_connect(hostname,  password, username, database);

<?php $con = mysqli_connect('localhost','root','','codingmantra'); ?>

 Step 3 :- Create view to upload file.

The following sample HTML code given below creates an uploader HTML form. This form is having a post method attribute set to action and the encrypted attribute is set to multipart/form-data (for upload a file)

<form method='post' action='' enctype='multipart/form-data'>
	<input type='file' name='image' class="form-control"><br>
	<input type='submit' value='Upload Image' class="btn btn-primary" name='upload'>    
</form>

Step 4:- Create Images folder to store images

Create new folder images for store uploaded images.

How to Compress Image size while Uploading in PHP

Step 5:- write compress code 

Here we use a compressedImage() function to compress PNG, JPEG and GIF images to save memory.

The function takes 3 parameters:-
1. Source
2. Destination
3. File quality

Execute imagejpeg() method to store image to the destination.

The third parameter is optional. It takes value from 0 – 100 and the default value is 75.

<?php
    
   if(isset($_POST['upload'])){

       // Getting file name
       $filename = $_FILES['image']['name'];
         
       // Valid extension
       $valid_ext = array('png','jpeg','jpg');

			
	   $photoExt1 = @end(explode('.', $filename)); // explode the image name to get the extension
	   $phototest1 = strtolower($photoExt1);
			
	   $new_profle_pic = time().'.'.$phototest1;
			
       // Location
       $location = "images/".$new_profle_pic;

       // file extension
       $file_extension = pathinfo($location, PATHINFO_EXTENSION);
       $file_extension = strtolower($file_extension);

       // Check extension
       if(in_array($file_extension,$valid_ext)){  

            // Compress Image
            compressedImage($_FILES['image']['tmp_name'],$location,60);
				
		    //Here i am enter the insert code in the step ........

        }
	    else
        {
                echo "File format is not correct.";
        }
    }

    // Compress image
    function compressedImage($source, $path, $quality) {

            $info = getimagesize($source);

            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, $path, $quality);

    }

 ?>

 

Step 6:- Now we are storing the image name in the database.

After that, we need to store image name into the database.

$sql = "INSERT INTO compress_image(image)VALUES ('".$new_profle_pic."')";
if (mysqli_query($con, $sql)) 
{
	echo "New record created successfully";
}

 

Ok everything is ok so we completed tutorials on Compress Image size while Uploading in PHP

 


About the author

user profile
Brijpal Sharma

Hello, My Name is Brijpal Sharma. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of Codermen. I started this blog to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers...

1 comments
Generic placeholder image
alexbeglov1989
August 05th, 2019 - 5:57PM

I will share my experience in image optimization ... At first, I had to manually compress all the pictures through Photoshop. The most free option by the way (except for the cost of a license for Photoshop). But this process takes a lot of time if there are more than 10-20 pictures on the site. After all, each picture must be manually processed, and then upload on the site again. Tedious such a process ... Now I use this service - https://optipic.io/ It saves a lot of time) It works by itself - automatically - only 1 time it needs to be connected to the site. Google is satisfied)

You must be logged in to post a comment.