Compress Images before upload in PHP

Rating: 5.0. From 3 votes.
Please wait...

Hey Friends,

We as developers usually get complaints from our client that the Media files are consuming lot of space than they should on the server resulting in choking the bandwidth of the server which in turns make website slow to load the main reason for this is “Uploading of huge media files especially images by the users on the website”. Now there are 2 scenarios by avoiding uploading of huge images on the website.

  1. First is to put the size limitation while uploading the file which is not as user-friendly since the user will have to compress the image or find some other alternative solution.
  2. The smart option is to compress the size of the image to the figure required by you automatically while uploading which will result in a smaller image acquiring less space on the server.

So today we have a quick hack on how you can compress the size of the image and upload it to the server as well as your database.

So lets start

  1. First let us create a simple form which from where we will upload the files

Filename: index.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PHP Hurdles Image Compression
<div>
<h2>PHP Hurdles Image Compression Tutorial</h2>
<div><form action="" enctype="multipart/form-data" method="post" name="hurdles"><input name="fileupload" size="25" type="file" />

<input id="mybut" name="Submit" type="submit" value="Upload" />

  <?php if($_POST){
            ?>
            <img src="<?php echo $filename; ?>" />    <!--For image Preview after upload-->
            <?php }
            ?>

</form></div>
</div>

2. The second step is to create database named “imageupload” and copy the below query to your SQL console to create a table named “image_data

1
2
3
4
CREATE TABLE IF NOT EXISTS `image_data` (
`id` int(11) NOT NULL,
`image` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

Now we will move to our coding part

3. Next step is to create database connection on index.php page

1
$connection = mysqli_connect('localhost','root','','imageupload')or die("error with database connection");

Now we will us take the input from the user and compress the image based on its type and upload it to database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$image =$_FILES["fileupload"]["name"];    //Get the image from user
$ex=explode('.',$image);      //explode image to get extension
$ext=end($ex);      //print the last array of above exploded string i.e extension of the image;
$uploadedfile = $_FILES['fileupload']['tmp_name'];  //Store image temp name in a variable
if ($image){
$extension = strtolower($ext);   //Convert all extensions in lower case
if($extension=="jpg" || $extension=="jpeg" )
{
$uploadedfile = $_FILES['fileupload']['tmp_name'];   //If image is of jpg or jpeg type store its temp name;
$src = imagecreatefromjpeg($uploadedfile);     // Returns image identifier if image is obtained from specified temp name location
}
else

if($extension=="png"){

$uploadedfile = $_FILES['fileupload']['tmp_name'];    //If image is of png type then use<strong> imagecreatefrompng</strong> to obtain image identifier from temp location

$src = imagecreatefrompng($uploadedfile);}

else {

$src = imagecreatefromgif($uploadedfile);    //else if image is of gif use <strong>imagecreatefromgif </strong>to obtain image identifier from temp location

}

list($width,$height)=getimagesize($uploadedfile);     //Get with and height of the image

$newwidth=200;                                                         //Set the new width in pixels.

$newheight=($height/$width)*$newwidth;        //Calculate new height obtained in ratio with new width

$tmp=imagecreatetruecolor($newwidth,$newheight);          //get new height and width of the image with black color

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);    //Resize the image

$filename = time().'_'.$newwidth.'_'.$newheight.'.'.$ext;

$filename1 = "images/". $filename;  //intoduce new file name to compressed image

imagejpeg($tmp,$filename1,100);   //Move image to specified location

imagedestroy($src);       //Destroy when work done

imagedestroy($tmp);

}

//Now upload new file to the database table

$res=mysqli_query($connection,"INSERT INTO image_data(image)VALUES('$filename')");

if($res>0)

{ echo "Uploaded";}

else

{ echo "failed";}

}

?>

So this is the simple way in which you can escape from putting burdern on your server space by using above quick snippet.

For source code of the above snippet Download Here

Hope this tutorial would help our fellow developers.

Because we believe Hurdles arn’t really Hurdles.

You can also view our other trending topic which can help you

Disable Past Dates Or Upcoming Dates In PHP Datepicker

Magento Server Migration

2 Comments

  1. Jim MacDiarmid said:

    Thank you for posting this. This is very helpful.

    Rating: 5.0. From 1 vote.
    Please wait...
    July 1, 2017
    Reply
    • Saurabh Dubey said:

      Thank You, Jim, We are glad to help you out.

      Rating: 3.0. From 1 vote.
      Please wait...
      July 1, 2017
      Reply

Leave a Reply

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