Image Compression in Laravel

Author - Webner
25.02.2020
|
0 Comments
||

image compression laravel

Steps to follow:

  1. Install the Intervention image package first in your project

    composer require intervention/image
    If you want to check official documentation of intervention image you can check it from here-
    http://image.intervention.io/getting_started/installation

  2. Inside the config/app.php-

    In providers, add:-
    Intervention\Image\ImageServiceProvider::class,
    In aliases, add:-
    'Image' => Intervention\Image\Facades\Image::class,

  3. Add namespace in your controller

    use Intervention\Image\ImageManagerStatic as Image;

  4. In your code use this when your file type is an image

    $s3 = Storage::disk('s3');
    $fileType = substr($file->getClientMimeType(), 0,5); //get file type of file
    if($fileType == 'image'){
    $fileSize = $image->getSize(); //get size of image file
    Log::info('Image size in bytes --- '.$fileSize);
    if($fileSize > 512000){
    Log::info('Image size is greater than 512 KB.');
    $actual_image = Image::make($image->getRealPath());
    $height = $actual_image->height()/4; //get 1/4th of image height
    $width = $actual_image->width()/4; //get 1/4th of image width
    $imageFile = $actual_image->resize($width, $height)->save($destinationPath . '/' . $fileName);
    //to resize image according to height width due to this file size is alo become less.
    $result = $s3->put($filePath,$actual_image); //to save file on s3 disk
    }else{
    Log::info('Image size is less than 512 KB.');
    $result = $s3->put ( $filePath, file_get_contents ( $image ) );
    }
    }

  5. Now images are compressed by 1/4th of the actual image size. You can check the compressed image on the S3 disk if you want.

FAQ

Is it possible to compress images in Laravel projects?

Yes, images can be compressed in Laravel projects using the Intervention Image package.

How much size is reduced using the Intervention Image package?

Images are compressed by 1/4th of the actual image size.

How can image compression help?

Image compression can improve a website's performance. A lot of programmers avoid compressing the images before they are stored in the database which makes their websites slow.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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