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

It is common to upload the images dynamically to the websites. But when we upload the large file size image on the website, it consumes a lot of time while loading. So the developer should write the code to reduce the image file size while uploading the image dynamically to the website. Using PHP, you can easily reduce the file size of those uploaded images during  time of upload. Of course, when reducing the file size we sacrifice the image quality.

Code to reduce file size for the image:

	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);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Read :How to Show a Preview of an Image Before Uploading it Using jQuery & JavaScript?


$info = getimagesize($source);


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 above functions are used to create a new image from the given file or URL. These functions are used to return an image identifier representing the image obtained from the given file name.

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

imagejpeg() function is used to create a JPEG file from the given image.

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

Quality ($quality): quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default range is 75.

The GD library is used for dynamic image creation. From PHP we use with the GD library to create GIF, PNG or JPG. This is very important to run all the image creation function in PHP. If your server doesn’t support the GD library then all the above functionality related to the image creation will not work.

Complete code to reduce the image file size:

	$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 = 'destination .jpg';

        			$filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
        			$buffer = file_get_contents($url);

        			/* Force download dialog... */
        			header("Content-Type: application/force-download");
        			header("Content-Type: application/octet-stream");
        			header("Content-Type: application/download");

			/* Don't allow caching... */
        			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

        			/* Set data type, size and filename */
        			header("Content-Type: application/octet-stream");
        			header("Content-Transfer-Encoding: binary");
        			header("Content-Length: " . strlen($buffer));
        			header("Content-Disposition: attachment; filename=$url");

        			/* Send our file... */
        			echo $buffer;
    		}else {
        			$error = "Uploaded image should be jpg or gif or png";
        		<title>Php code compress the image</title>

		<div class="message">
                        		if ($error) {
                            		<label class="error"><?php echo $error; ?></label>
		<fieldset class="well">
            	    	<legend>Upload Image:</legend>                
			<form action="" name="myform" id="myform" method="post" enctype="multipart/form-data">
			                                <input type="file" name="file" id="file"/>
						<input type="submit" name="submit" id="submit" class="submit btn-success"/>

I hope the above-mentioned PHP code could be beneficial in reducing the image file size while uploading it to save your precious time. I believe the topic discussed here is quite useful to everyone who reads it!

Realated Posts

21 thoughts on “How to Reduce Image File Size while Uploading Using PHP code?

  1. Sadick

    Thanks for the code! they are working fine and manage to reduce file uploaded. I have one problem, I wish to store the compressed files in the server and not download them. I have tried playing around with the code but I could not do it. Where or how am I supposed to edit the code above if I want to files I upload to be compressed and then stored in a given destination in the server (NOT DOWNLOAD THE FILE)

    • balasubramaniam

      In the above code hide the headers code and add the absolute path for the $url veriable.


      Remove / Hide the below code

      $url = ‘destination .jpg’;
      $filename = compress_image($_FILES["file"]["tmp_name"], $url, 80);
      $buffer = file_get_contents($url);
      /* Force download dialog… */
      header(“Content-Type: application/force-download”);
      header(“Content-Type: application/octet-stream”);
      header(“Content-Type: application/download”);
      /* Don’t allow caching… */
      header(“Cache-Control: must-revalidate, post-check=0, pre-check=0″);
      /* Set data type, size and filename */
      header(“Content-Type: application/octet-stream”);
      header(“Content-Transfer-Encoding: binary”);
      header(“Content-Length: ” . strlen($buffer));
      header(“Content-Disposition: attachment; filename=$url”);
      /* Send our file… */
      echo $buffer;

      and add the below code,

      $url = ‘C:/Users/user/Downloads/destination.jpg’;

      This is the absolute path that where your image will be store.

  2. Khushi

    very helping code..
    and if it is possible then please provide us audio video compression module also..

  3. Zella Whilite

    To reduce Image size the file and Image types need to shrink with same same quality, so that the size can e reduced. The above information makes more tweaked about reducing image size with PHP. Nice one.

  4. Steve Benete

    Really, an Interesting article and it’ll be very helpful like mine of people who using Image size reduction.

  5. jai

    Is there any bug in the code? downloaded image is corrupted!pls help!

  6. Hector Perales

    Many thanks for being so helpful! Just learned a unique process on image reducing. Keep more like this to enhance all other readers.

  7. John

    Thanks for the awesome post, really it will help us a lot to reduce the file size.

    Kind Regards

  8. Abdex

    Thank you very much ! It was so Helpful !
    All Kind Regards

    • Ramanathan

      Hello Abdex,

      Its good to hear you! Also, visit our other technical blogs to know more.


  9. Sandeep

    Nice information it’s working.

    • Ramanathan

      Hi Sandeep,

      Thanks for your comment and also have a look on other technical blog posts.


  10. Dieg

    Awesome, worked perfectly. Thank you very much!!!!!!

    • Ramanathan

      Hello Dieg,

      Glad it helped for you. Also check our recent articles and stay tuned.


  11. Ganesh

    The downloaded file is not in the format what i had uploaded.
    Is it possible that compressed image have same extension like uploaded.
    Please help.

    • Ramanathan

      Dear Ganesh,

      While copying the code, you will get space and it doesn’t work. Remove the spaces and check the source code as given above. Sure, it will work.

      If any assistance, let me know.

  12. Ganesh


    Actually its my mistake. copied code so get space between “destination” and “.jpg”


  13. Mariappan

    Its Very use full one.Thank lot Buddy :)

    • Ramanathan


      Great to hear from you. Hope it helped you for implementing. Kepp track on our latest updates too.

  14. Aldo Zapata

    Hi, very, very nice, adapted to my actual code, upload image > move to folder > create thumbnail > Compress Image > link form Thb to compressed image :)

  15. Mossy Omoyeni

    Thanks a bunch Ramanathan, this is just awesome, quality remaineth while the size is over 300% reduced. God bless!

Leave a Reply

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



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">