28 March, 2024
Image File Size

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:

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

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?

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 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.

Note:
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:

<?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 = '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";
    		}
	}
?>
<html>
    	<head>
        		<title>Php code compress the image</title>
    	</head>
    	<body>

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

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!

Alex Sam is a digital marketer by choice & profession. He munches on topics relating to technology, eCommerce, enterprise mobility, Cloud Solutions and Internet of Things. His other interests lies in SEO, Online Reputation Management and Google Analytics. Follow Me Socially: Habr , Dev.to & Viblo .

21 Comments

  1. Sadick Reply

    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)

    1. balasubramaniam Reply

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

      Examble:

      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. Zella Whilite Reply

    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.

  3. Hector Perales Reply

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

  4. Ganesh Reply

    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.

    1. Ramanathan Reply

      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.

    1. Ramanathan Reply

      Mariappan,

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

  5. Aldo Zapata Reply

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

Leave a Reply

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