Image optimization can greatly improve site performance, and is one of the most common issues I see in Google pagespeed insights reports. Sometimes images can be reduced by 50% or more, yet, it can be difficult to string various tools together to optimize images in web applications.

For this short snippet tutorial, we’ll be using Spatie Image Optimizer Laravel Package to quickly setup image optimization in our Laravel project.

Pre-requisites

This package make use of few optimization tools to get going. Installation may vary depends on your operating system. We’ll install the following optimization tools on Mac & Ubuntu.

  • jpegoptim
  • optipng
  • pngquant
  • svgo
  • gifsicle
  • webp

Installing Optimizing Tools on Ubuntu

sudo apt-get install jpegoptim
sudo apt-get install optipng
sudo apt-get install pngquant
sudo npm install -g svgo
sudo apt-get install gifsicle
sudo apt-get install webp

Installing Optimizing Tools on Mac

brew install jpegoptim
brew install optipng
brew install pngquant
brew install svgo
brew install gifsicle
brew install webp

Installing package in your Laravel application

In this step, we’ll install this image optimization package in our Laravel application.

composer require spatie/laravel-image-optimizer

Optimize Images right away

Now, back in your controller where you’re storing or playing around with image, we’ll add our optimzer and process our images through it.

foreach ($images as $image) {
    Image::create([
        'src' => $image->hashName(),
    ]);
    $optimizerChain = OptimizerChainFactory::create();
    $optimizerChain->optimize($image);
    Storage::disk('s3')->put('optimized/images/', $image, 'public');
}

Pro Tip: Check the optimization percentage

Ever wondered how many percent does this package shrink your image? We can do it for testing by simple code snippet.

$originalSize = filesize($image);
                $optimizerChain = OptimizerChainFactory::create();
                $optimizerChain->optimize($image);
                $optimizedSize = filesize($image);
                $percentChange = (1 - $optimizedSize /  $originalSize) * 100;
                echo sprintf("The image is now %.2f%% smaller\n", $percentChange);

You may also Like