Compress Image Size In PHP.

 The large size image may take more time to upload on a server. It also takes more time to load on a page. So it is good practice to minimize the image size before upload on the server. Usually, the user does not optimize the image when uploading through the website. In this case, our application should be able  to optimize the image before upload on the server.

 In this tutorial, We will learn image compression techniques  by using the PHP function. This script is used to optimize the images while uploading in PHP. By using PHP functions we can easily implement image compression.

To improve the website loading speed image should be compressed. So we can use the above technique to compress an image before uploading the image.

<?php
if(isset($_POST['upload'])){

      $imagename   = $_FILES['upload_image']['name'];
      $allowed_extension  = array('png','jpeg','jpg');  
      $path  = "uploads/".$imagename   ;  
     $extension   = pathinfo($location, PATHINFO_EXTENSION);
 
    if(in_array($allowed_extension,$extension   )){  
    //Compress Image Code
      compressImage($_FILES['upload_image']['tmp_name'],$path ,70);  
    }else{
      echo "Invalid file type.";
    }
  }
  
  // Compress image
  function compressImage($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);    
  }
?>
<html>
<body>
<form method='post' action='' enctype='multipart/form-data'>
  <input type='file' name='upload_image' >
  <input type='submit' value='Upload' name='upload'> 
</form>
</body>
</html>

The post How To Compress Image Size Before Uploading In PHP. appeared first on PHPFOREVER.

Categories: PHP