How to reduce or compress image size while uploading using PHP

  •  
  •  
  •  
  •  
  •  
  •  

It is very common to upload images to the server or website by the users and admins. Users mostly upload their images for setting their profile picture or to submit documents and so on. But most of the time images are uploaded by the users are not optimized for the web, thus taking much more spaces on your server than that it actually need. Apart from this when you upload an image of large size, it takes more time to load on the web page, thus its effects on your website ranking.

Uploaded images are very important and it should be reduced as much as possible. You can write some PHP code that reduces or compress image size while uploading to the server. But, of course reducing the image size will also reduce the image quality.  So, in this tutorial, I will show you how to reduce or compress image size while uploading using PHP.

How to reduce or compress image size while uploading using PHP

Step 1: Image Upload Form (index.php)

<form method="post" enctype="multipart/form-data">
  <table width="500" border="0">
    <tr>
    <td><label>Upload image <font color="#FF0000;">*</font></label><input type="file" name="uploadImg" value="" /></td>
    </tr>
    <tr>
    <td><label>New width</label><input type="text" name="width" value=""></td>
    </tr>
    <tr>
    <td><label>New height</label><input type="text" name="height" value=""></td>
    </tr>
    <tr>
    <td><label>Image quality</label><input type="text" name="quality" value=""></td>
    </tr>
    <tr>
    <td><input type="submit" name="submit" value="Upload & Compress" /></td>
    </tr>
  </table>
</form>

The above simple HTML code allows the users to browse, choose and then upload the image to the website or server. Also, you can create a new image by providing new height, width and image quality. If you want to create the new image of same width and height as the original one then leave these fields blank.

Step 2: Validation Image Before Upload To Server (index.php)

<?php
   $success = false;
   if(isset($_POST['submit']) && !empty($_POST['submit'])) {
       if(isset($_FILES['uploadImg']['name']) && @$_FILES['uploadImg']['name'] != "") {
           if($_FILES['uploadImg']['error'] > 0) {
              echo '<h4>Increase post_max_size and upload_max_filesize limit in php.ini file.</h4>';
           } else {
               if($_FILES['uploadImg']['size'] / 1024 <= 5120) { // 5MB
                  if($_FILES['uploadImg']['type'] == 'image/jpeg' || 
                     $_FILES['uploadImg']['type'] == 'image/pjpeg' || 
                     $_FILES['uploadImg']['type'] == 'image/png' ||
                     $_FILES['uploadImg']['type'] == 'image/gif'){
                  
                        $source_file = $_FILES['uploadImg']['tmp_name'];
                        $target_file = "uploads/compressed_" . $_FILES['uploadImg']['name']; 
                        $width      = $_POST['width'];
                        $height     = $_POST['height'];
                        $quality    = $_POST['quality'];
                        //$image_name = $_FILES['uploadImg']['name'];
                        $success = compress_image($source_file, $target_file, $width, $height, $quality);
                        if($success) {
                          // Optional. The original file is uploaded to the server only for the comparison purpose.
                          copy($source_file, "uploads/original_" . $_FILES['uploadImg']['name']);
                        }
                  }
              } else {
                  echo '<h4>Image should be maximun 2MB in size!</h4>';
              }
            }
         } else {
            echo "<h4>Please select an image first!</h4>";
         }
    }
?>

If any error occurred then you have to increase the limit of post_max_size and upload_max_filesize variables in php.ini file.

Step 3: Reduce Or Compress Image size while Upload (index.php)

<?php
function compress_image($source_file, $target_file, $nwidth, $nheight, $quality) {
  //Return an array consisting of image type, height, widh and mime type.
  $image_info = getimagesize($source_file);
  if(!($nwidth > 0)) $nwidth = $image_info[0];
  if(!($nheight > 0)) $nheight = $image_info[1];
  
  if(!empty($image_info)) {
    switch($image_info['mime']) {
      case 'image/jpeg' :
        if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefromjpeg($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        //Output image to the browser or file.
        return imagejpeg($thumb, $target_file, $quality); 
        
        break;
      
      case 'image/png' :
        if($quality == '' || $quality < 0 || $quality > 9) $quality = 6; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefrompng($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        // Output image to the browser or file.
        return imagepng($thumb, $target_file, $quality);
        break;
        
      case 'image/gif' :
        if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefromgif($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        // Output image to the browser or file.
        return imagegif($thumb, $target_file, $quality); //$success = true;
        break;
        
      default:
        echo "<h4>File type not supported!</h4>";
        break;
    }
  }
}
?>

getimagesize(..) – Returns the dimensions along with the file type and a height/width text string to be used inside a normal HTML img tag and the correspondent HTTP content type.

imagecreatefromjpeg(..) / imagecreatefrompng(..)imagecreatefromgif(..)– These functions create a new image from the file or URL passing through it as parameter.

imagecreatetruecolor(..)– This function is used to create a new true color image.

imagecopyresized(..)– This function copy and resize an image by providing the new height and width as parameters.

imagejpeg(…) / imagepng(…) / imagegif(…) – These functions output the image to the browser or file.  They take three parameters. The first one is the true color image created by the imagecreatetruecolor() function. The second parameter is the image name with location. And the third parameter is the quality of the image you want. It varies from 0 – 100 for .jpg and .gif images. For .png files, it varies from 0-6.

copy(..) – It uploads the original file to the server, only for the comparison purpose.

Complete Source Code – Reduce Or Compress Image Size While Uploading Using PHP

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>How to reduce or compress image size while uploading using PHP | Mitrajit's Tech Blog</title>
  </head>
  	<style>
  span { clear:both; display:block; margin-bottom:30px; }
  span a { font-weight:bold; color:#0099FF; }
  img { max-width:150px; padding:3px; border:2px solid #eee; border-radius:3px;}
  table td { padding-bottom:10px;}
  label { display:block; font-weight:bold; padding-bottom:3px }
  p.red { color:#FF0000; }
  </style>
  <body>
  <div class="container-fluid">
    <span class="top-margin">Read the full article on -- <a href="http://www.mitrajit.com/reduce-or-compress-image-size-while-uploading-using-php/" target="_blank">Live demo on Reduce or compress image size while uploading using PHP</a> in <a href="http://www.mitrajit.com/">Mitrajit's Tech Blog</a></span>
    
    <div class="row">
      <div class="col-md-6 col-xs-12">
        Note : 
        <ul>
          <li>Allowed image types are -- .jpg|.jpeg|.gif|.png.</li>
          <li>New width, height and quality are optional.</li>
          <li>New width and height should be greater than 0.</li>
          <li>Image quality range should in between 0-100 for .jpg and .gif images.</li>
          <li>Image quality range should in between 0-9 for .png images.</li>
        </ul> 
      </div>
      
      <div class="col-md-6 col-xs-12">
        <form method="post" enctype="multipart/form-data">
          <table width="500" border="0">
            <tr>
            <td><label>Upload image <font color="#FF0000;">*</font></label><input type="file" name="uploadImg" value="" /></td>
            </tr>
            <tr>
            <td><label>New width</label><input type="text" name="width" value=""></td>
            </tr>
            <tr>
            <td><label>New height</label><input type="text" name="height" value=""></td>
            </tr>
            <tr>
            <td><label>Image quality</label><input type="text" name="quality" value=""></td>
            </tr>
            <tr>
            <td><input type="submit" name="submit" value="Upload & Compress" /></td>
            </tr>
          </table>
        </form>
      </div>
    </div>
    
    <div class="row">
      <div class="col-md-12">
        <?php
        $success = false;
        if(isset($_POST['submit']) && !empty($_POST['submit'])) {
          if(isset($_FILES['uploadImg']['name']) && @$_FILES['uploadImg']['name'] != "") {
            if($_FILES['uploadImg']['error'] > 0) {
              echo '<h4>Increase post_max_size and upload_max_filesize limit in php.ini file.</h4>';
            } else {
              if($_FILES['uploadImg']['size'] / 1024 <= 5120) { // 5MB
                if($_FILES['uploadImg']['type'] == 'image/jpeg' || 
                   $_FILES['uploadImg']['type'] == 'image/pjpeg' || 
                   $_FILES['uploadImg']['type'] == 'image/png' ||
                   $_FILES['uploadImg']['type'] == 'image/gif'){
                  
                  $source_file = $_FILES['uploadImg']['tmp_name'];
                  $target_file = "uploads/compressed_" . $_FILES['uploadImg']['name']; 
                  $width      = $_POST['width'];
                  $height     = $_POST['height'];
                  $quality    = $_POST['quality'];
                  //$image_name = $_FILES['uploadImg']['name'];
                  $success = compress_image($source_file, $target_file, $width, $height, $quality);
                  if($success) {
                    // Optional. The original file is uploaded to the server only for the comparison purpose.
                    copy($source_file, "uploads/original_" . $_FILES['uploadImg']['name']);
                  }
                }
              } else {
                echo '<h4>Image should be maximun 5MB in size!</h4>';
              }
            }
          } else {
            echo "<h4>Please select an image first!</h4>";
          }
        }
        ?>
        
        <!-- Displaying original and compressed images -->
        <?php if($success) { ?>
        <?php $destination = "uploads/"; ?>
          <table border="0" cellpadding="20">
            <tr>
            <td>
              <a href="<?php echo $destination . "original_" . $_FILES['uploadImg']['name']?>" target="_blank" title="View actual size">
                <img src='<?php echo $destination . "original_" . $_FILES['uploadImg']['name']?>'>
              </a><br>
              Original : <?php echo round(filesize($destination . "original_" . $_FILES['uploadImg']['name'])/1024,2); ?>KB
            </td>
            <td>
              <a href="<?php echo $destination . "compressed_" . $_FILES['uploadImg']['name']?>" target="_blank" title="View actual size">
                <img src='<?php echo $destination . "compressed_" . $_FILES['uploadImg']['name']?>'>
              </a><br>
              Compressed : <?php echo round(filesize($destination . "compressed_" . $_FILES['uploadImg']['name'])/1024, 2); ?>KB
            </td>
            </tr>
          </table>
        <?php } ?>
      </div>
    </div>
      
      
      
      
      
      
      
<?php
function compress_image($source_file, $target_file, $nwidth, $nheight, $quality) {
  //Return an array consisting of image type, height, widh and mime type.
  $image_info = getimagesize($source_file);
  if(!($nwidth > 0)) $nwidth = $image_info[0];
  if(!($nheight > 0)) $nheight = $image_info[1];
  

  if(!empty($image_info)) {
    switch($image_info['mime']) {
      case 'image/jpeg' :
        if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefromjpeg($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        // Output image to the browser or file.
        return imagejpeg($thumb, $target_file, $quality); 
        
        break;
      
      case 'image/png' :
        if($quality == '' || $quality < 0 || $quality > 9) $quality = 6; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefrompng($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        // Output image to the browser or file.
        return imagepng($thumb, $target_file, $quality);
        break;
        
      case 'image/gif' :
        if($quality == '' || $quality < 0 || $quality > 100) $quality = 75; //Default quality
        // Create a new image from the file or the url.
        $image = imagecreatefromgif($source_file);
        $thumb = imagecreatetruecolor($nwidth, $nheight);
        //Resize the $thumb image
        imagecopyresized($thumb, $image, 0, 0, 0, 0, $nwidth, $nheight, $image_info[0], $image_info[1]);
        // Output image to the browser or file.
        return imagegif($thumb, $target_file, $quality); //$success = true;
        break;
        
      default:
        echo "<h4>Not supported file type!</h4>";
        break;
    }
  }
}
?>
</body>

Try the live demo example from the Demo link. Also, you can download the complete source code from the below Download link. Please like and share this tutorial with others.

About Mitrajit

0 comments on “How to reduce or compress image size while uploading using PHP

  1. Maybe an idea to write some information about Thumbor image tools. I am using it for a little while now and it is really great all options available by using this.

    I didnt see any posts from 2018. When you like it you have some info 😉

Leave a Reply

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

Prove you are a human *