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.

      <form action="" method="POST" enctype ="multipart/form-data">
		<input type="file" name="file_name" />
		<input type="submit"/>
		<?php if(isset($_FILES['file_name'])){	 ?>
            <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'] ?>
		<?php } ?>	

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

      $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']);
      $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) {
		//echo "Success";
		$save = "images/sml_" . $file_name; //This is the new file you saving
		$file = "images/" . $file_name; //This is the original file
		$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);
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

Leave a Reply