How to compress image while uploading using php

How to compress image while uploading using php

The functionality of image uploading is common in web projects that allow users to upload images to set the profile picture or to maintain their image gallery.

Mostly large image files are uploaded and this requires too much time and ranking of the website effects. So the images that have been uploaded are very relevant and should be that as much as possible.

So in this tutorial, you'll learn how to minimize or compress the image size when uploading using PHP without losing quality With live demo and link to download source code the tutorial is explained in very easy steps.

Let's start the coding, then. We will have the following file structure to minimize or compress image size when uploading using PHP, without losing quality.

  • index.php
  • upload.js
  • upload.php

Steps1: Create Image Upload Form

We'll first create HTML image upload form in index.php. When submitting a form, we'll handle image upload in upload.php.

<div class="container">
  <h2>Reduce or Compress Image Size While Uploading in PHP</h2>
  <form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="upload.php">
  	<label>Choose Images to Upload</label>
  	<input type="file" name="upload_images" id="image_file">
  	<div class="file_uploading hidden">
  		<label> </label>
  		<img src="uploading.gif" alt="Uploading......"/>
  	</div>
  </form>
  <div id="uploaded_images_preview"></div>
</div>

Steps2: Using jQuery to handle image upload form submit

As we are going to handle submitting form using plugin jQuery Form, we need to include plugin files.

<script type="text/javascript" src="scripts/jquery.form.js"></script>
<script type="text/javascript" src="scripts/upload.js"></script>

Steps3: Handle Image Upload Form Submit using jQuery

Using jQuery change event will handle the submit image upload form.

$(document).ready(function(){
  $('#image_file').on('change',function(){
    $('#upload_form').ajaxForm({
      target:'#uploaded_images_preview',
      beforeSubmit:function(e){
      	$('.file_uploading').show();
      },
      success:function(e){
      	$('.file_uploading').hide();
      },
      	error:function(e){
      }
    }).submit();
  });
});

Steps4: Perform Image Upload and Image Compress

In upload.php, we'll eventually perform the image upload and compress functions.

We have developed the function compressImage() to compress the image files "JPG, GIF or PNG".

In PHP image compress functions we passed the default image quality value. The default value of the image quality can be adjusted according to the requirement of image quality. Below is full PHP code with image upload and compress function.

We are uploading the original image file in this example code and then compressing that image file and renaming it in the same directory with "min-".

<?php
$file_type_error = '';
if ($_FILES['upload_images']['name']) {
    $upload_dir = "uploads/";
    if (($_FILES["upload_images"]["type"] == "image/gif") || ($_FILES["upload_images"]["type"] == "image/jpeg") || ($_FILES["upload_images"]["type"] == "image/png") || ($_FILES["upload_images"]["type"] == "image/pjpeg")) {
        $file_name   = $_FILES["upload_images"]["name"];
        $extension   = end((explode(".", $file_name)));
        $upload_file = $upload_dir . $file_name;
        if (move_uploaded_file($_FILES['upload_images']['tmp_name'], $upload_file)) {
            $source_image      = $upload_file;
            $image_destination = $upload_dir . "min-" . $file_name;
            $compress_images   = compressImage($source_image, $image_destination);
        }
    } else {
        $file_type_error = "Upload only jpg or gif or png file type";
    }
}
// created compressed JPEG file from source file
function compressImage($source_image, $compress_image)
{
    $image_info = getimagesize($source_image);
    if ($image_info['mime'] == 'image/jpeg') {
        $source_image = imagecreatefromjpeg($source_image);
        imagejpeg($source_image, $compress_image, 75);
    } elseif ($image_info['mime'] == 'image/gif') {
        $source_image = imagecreatefromgif($source_image);
        imagegif($source_image, $compress_image, 75);
    } elseif ($image_info['mime'] == 'image/png') {
        $source_image = imagecreatefrompng($source_image);
        imagepng($source_image, $compress_image, 6);
    }
    return $compress_image;
}
?>

If you find this article helpful, don’t forget to share it with your friends. And stay updated with us by subscribing our blog.

Leave comment

Comments (1)

// SEARCH

What are you searching for....?

// SUBSCRIBE

Subscribe to us on youtube for updates of our videos first on youtube.

// SUBSCRIBE

To receive updates on the latest news, tutorials and special offers, subscribe to our email newsletter today!

// CATEGORIES

x
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Privacy Policy That's Fine