Compress Image Size While uploading in Codeigniter

 Image compression is very helpful to reduce the size of the image. In the image compress functionality, the file size is reduced before upload.

The compressImage() is a custom function that helps to compress and save image on the server using PHP. This function accepts the following parameters and returns the compressed image.

  • *file_name - An image file source to compress size.
  • An image file source to compress size.
  • $file_path – Server path to save the compressed image.
  • $quality - An image file source to compress size.

Code:

function compress_image($file_name, $file_path, $quality) {

$imgInfo = getimagesize($tempPath);

$mime = $imgInfo['mime'];

// Create a new image from file

switch($mime) {

case 'image/jpeg':

$image = imagecreatefromjpeg($tempPath);

break;

case 'image/png':

$image = imagecreatefrompng($tempPath);

break;

case 'image/gif':

$image = imagecreatefromgif($tempPath);

break;

default:

$image = imagecreatefromjpeg($tempPath);

}

// Save image imagejpeg($image, $originalPath, $quality);

// Return compressed image

return $originalPath;

}

Get the Image from the form data using the html form.

if(isset($_POST["submit"])){ 
        if(!empty($_FILES["image"]["name"])) { 
        $fileName = $_FILES["image"]["name"]); 
         $uploadPath = 'uploads/user'
        $imageUploadPath = $uploadPath . $fileName; 
    
            $imageTemp = $_FILES["image"]["tmp_name"];              
            // Compress size and upload image 
            $compressedImage = compressImage($imageTemp, $imageUploadPath, 75); 
            if($compressedImage){ 
                $compressedImageSize = filesize($compressedImage); 
                $compressedImageSize = convert_filesize($compressedImageSize);     
               
            }else{ 
                $statusMsg = "Image compress failed!"; 
            } 
       
   
}

Here is the Simple code to compress the image using codiginator.

Thanks for reading this article.

Regrads,

Rajamohan.

Sign In or Register to comment.