How to Reduce or Compress Image File Size while Uploading Using PHP code?

REDUCE-IMAGE
 

It is a quite common process to upload images on the websites dynamically. However, while you upload the image with large file size in a website, it is likely to take more time to load. This necessitates the developer to write down the code to decrease the file size of image while dynamically uploading the image to the website. With the help of PHP coding, it is possible to reduce the size of files of uploaded images when they are loading. Definitely, you would have to compromise with the image quality i.e. is the file size has to be reduced. 

Below is the Code to reduce file size for the image:

<?php 
	function compress($source, $destination, $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, $destination, $quality);

		return $destination;
	}

	$source_img = 'source.jpg';
	$destination_img = 'destination .jpg';

	$d = compress($source_img, $destination_img, 90);
 ?>
$d = compress($source_img, $destination_img, 90);

PHP function is used in the code that will pass the source image, destination image and quality for the image that takes to compress.

$info = getimagesize($source);

The getimagesize() function is also used to know the size of given image file and to return the dimensions including the file type.
Example:

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

Output:

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

All the functions used in the coding are intended to make a new image from the given URL or file. Those functions are meant for returning an image identifier indicating the image acquired from the given file name.

imagejpeg($image, $destination, $quality);

The imagejpeg() function is added in the code to make a JPEG file from the provided image.

Syntax: imagejpeg ( $source_image, $destination_image, $quality )

Quality ($quality): Quality is optional that range from 0 representing the worst quality and smaller file to hundred representing the best quality and biggest file. The range75 is considered as the default.
Note:
The GD library is utilized for creating dynamic image. GD library is used to create JPG, PNG or GIF. This is more essential to run every image creation function in PHP language. When your server is not compatible with GD library, then the complete functionality associated with the image creation won’t work out.

Here is the Complete code to reduce the image file size using PHP:

<?php
$name = ''; $type = ''; $size = ''; $error = '';
   function compress_image($source_url, $destination_url, $quality) {

      $info = getimagesize($source_url);

          if ($info['mime'] == 'image/jpeg')
          $image = imagecreatefromjpeg($source_url);

          elseif ($info['mime'] == 'image/gif')
          $image = imagecreatefromgif($source_url);

          elseif ($info['mime'] == 'image/png')
          $image = imagecreatefrompng($source_url);

          imagejpeg($image, $destination_url, $quality);
          return $destination_url;
        }

            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") ||
            ($_FILES["file"]["type"] == "image/pjpeg")) {

            $url = 'C:/Users/admin/Downloads/compressed.jpg';
            $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
        }else {
            $error = "Uploaded image should be jpg or gif or png";
        }
        }
?>
<html>
    <head>
        <title>Php code compress the image</title>
    </head>
    <body>

        <div class="error">
            <?php
                if($_POST){
                  if ($error) {
            ?>
            <label class="error"><?php echo $error; ?></label>
            <?php
            }
         }
       ?>
       </div>
           <fieldset class="well">
               <legend>Upload Image:</legend>
                   <form action="" name="img_compress" id="img_compress" 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 btn-success"/>
                           </li>
                       </ul>
                  </form>
           </fieldset>
     </body>
</html>

The PHP code is beneficial in decreasing the file size of image, while uploading it to save your valuable time.

31 Responses so far.

  1. Ruby says:
    I have successfully reduced the image file size before uploading to my website, this php code worked finely. Thanks for this.
  2. Ashok Patel says:
    Nice post! I was searching for How to Compress Image File Size Using PHP code and finally got a solution. Thanks it helped me a lot to compress my image file size in php and now I uploaded it in my website.
  3. Krish says:
    Interesting article and worked successfully for my website, helped me to reduce image file size using php code, can you provide the same for video compression?
  4. peter says:
    Informative post for who wants to compress the image file size in php.
  5. Dheepan DIna says:
    Good scritpt for compressing the image file size while uploading to the website using php code. As this script does not contains any js files, this was very helpful because we only uses php code for work.
  6. sathick says:
    Thank you for the great Php code script. This article would be help full for all who is finding it difficult to reduce image file size in php for their website..
  7. Aaslin says:
    I was a java programmer and presently started to work in PHP.. This article helped me a lot to compress image file size in php for my website using this source code.
  8. selina says:
    This code worked finely for me thanks for the blog to reduce the image file size.
  9. vivek says:
    Thanks for the Php code, its working fine and helped me to compress image file size for my website.
  10. G. Putra says:
    Thank you for the code, its awesome code. I would like to use it in future my application
  11. Aparna says:
    Thanks for the php script to reduce the image file size. It helped for my website to optimize my speed too as i compressed the image file size and then uploaded in my website.
  12. Aliens says:
    Very helpful while searching around to compress images so your website loads fast and don’t visitors keep wait long. Very nice research n doing.
    its Woo PHP image code
  13. Plexure says:
    Good php script for reducing the image file size with php , but can you suggest the same using javascript?
  14. Phorani says:
    I am new to PHP and was feeling difficult to resize the image while uploading it, at the right time found a simple code and useful article which helped me to compress image file size using PHP while uploading to my website. This worked great! Thank you
  15. Joyce says:
    Good blog on compressing the image file size while uploading to your website using PHP code. Expecting more useful article likewise. I am following all your posts you put on your blog. Keep up the work going.
  16. Angelia says:
    i was searching for this query for long time , executed some codes, but i had no right solution. Let me try out this for reducing image file size while uploading it to website and check whether this is working fine for me..
  17. Henry says:
    I will give it a try. Was looking for this image compression function for uploading it in my website.
  18. Malik says:
    What is the use of reducing or compressing image file size while you upload it your website? As i am not aware of this topic i am keeping this question in front.
  19. Della says:
    Reducing image file size is an difficult one or what?? Why to use PHP code for compressing image size? can some one explain this as i am not aware of.
  20. Ganesh Rahul says:
    Nice Post. Can you give me a code to convert any image to .webp format?
    I have tried with ‘imagewebp();’

    I have error while using this,
    Fatal error: Uncaught Error: Call to undefined function imagewebp().

    I have XAMPP for Linux 7.0.8*
    And enabled with GD Support.

    I want to enable webp support.
    What I want to do?
    Can you help me out

  21. It’s nice solution for 2-3 mb images to use the PHP GD library but if you have high traffic and thousands of users uploading you will suffer.. I have expirienced it myself. We swiched the model to compress/resize images on client browser with HTML5 Canvas resize and than send it to server as Base64 string. The server uses GD just to store it az JPG. Just my experience.
  22. Eliza says:
    Good post on reducing the image file size while you upload to your website. Keep the good work.
  23. Jason says:
    I have been browsing online greater than three hours nowadays, but I by no means
    found any interesting article like yours. It’s pretty price sufficient for me.
    In my opinion, if all webmasters and bloggers made excellent content as you
    did, the net will likely be a lot more helpful than ever before.
  24. Jane says:
    Compressing image file size is really very simple using this PHP code. I would recommend others to try out this code too for their website before they upload images .
  25. Chandrasena says:
    can i know what is the use of reducing or compressing image file size when uploading to website??
  26. BeaGBockrath says:
    Good post. I learn something totally new and challenging on blogs I
    stumbleupon every day. It’s always helpful to
    read articles from other authors and use a
    little something from other websites.
  27. DorrisQLakin says:
    I feel this is one of the a great deal important information to me.
    And i am glad reading your article on how to reduce image file size. However should
    statement on few normal issues, The website style is
    perfect, the articles is truly nice : D. Good activity,
    cheers
  28. JaeYKapsos says:
    Great post on reducing image size using php! We are going to be linking to the great content
    on our site. Maintain the great writing.
  29. LanetteIHitt says:
    Great article! We shall be linking to this great content on our website.
    Continue the excellent writing.
  30. TrumanXZeger says:
    Good post but I was wondering if you could write a litte more on this
    subject? I’d be very grateful if you could elaborate a little bit
    more. Bless you!
  31. Sumit says:
    Good script! I used this script and its successfully compress the image file. But png image will not open after compression because the type of png image is remain Jpeg. Please give the solution for same.

    Thanks

LEAVE A COMMENT