How to compress image size while uploading in PHP

Compress image size while uploading in PHP, It’s really good for page speed and SEO thing. We will perform this without losing quality of image. So, let’s have begin to create HTML form.

Create index.php file.

<html>
   <body>
      
      <form action="" method="POST" enctype ="multipart/form-data">
		<input type="file" name="file_name" />
		<input type="submit"/>
		
		<?php if(isset($_FILES['file_name'])){	 ?>
         <ul>
            <li>Sent file: <?php echo $_FILES['file_name']['name'];  ?>
            <li>File size: <?php echo $_FILES['file_name']['size'];  ?>
            <li>File type: <?php echo $_FILES['file_name']['type'] ?>
         </ul>
		<?php } ?>	
      </form>
      
   </body>
</html>

Create form submit in PHP add below snipper to top of the HTML.

<?php
if(isset($_FILES['file_name'])){
      $errors= array();
      $file_name = $_FILES['file_name']['name'];
      $file_size = $_FILES['file_name']['size'];
      $file_tmp = $_FILES['file_name']['tmp_name'];
      $file_type = $_FILES['file_name']['type'];$file_array=explode('.',$_FILES['file_name']['name']);
      $file_ext=strtolower(end($file_array));
      
	  
		  
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 500000) {
         $errors[]='Sorry, your file is too large';
      }
      
      if(empty($errors)==true) {
         if(move_uploaded_file($file_tmp,"images/".$file_name)){
		//echo "Success";
		$save = "images/sml_" . $file_name; //This is the new file you saving
		$file = "images/" . $file_name; //This is the original file
		$quality=75;
		$info = getimagesize($file);

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

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

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

			imagejpeg($image, $save, $quality);
		}
         
      }else{
         print_r($errors);
      }
   }
?>
Read Also: PHP file upload in database with Error Handling
Read Also: How to submit form without page refresh using PHP, jQuery and Ajax

You can set quality by $quality this variable. final output

Final Output

How to compress image size while uploading in PHP

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply