We are going to be using multiple image compressors, so please make sure that you have the following bins installed.
╰─$ which svgo pngquant optipng jpegoptim gifsicle convert
/usr/local/bin/svgo
/usr/local/bin/pngquant
/usr/local/bin/optipng
/usr/local/bin/jpegoptim
/usr/local/bin/gifsicle
/usr/local/bin/convert
Follow the instructions given here to install all binaries( note: sudo amazon-linux-extras install epel):
https://github.com/spatie/image-optimizer
You may need to install epel-release:
yum install epel-release
Next, let’s install, Spatie’s Laravel image optimizer.
composer require spatie/laravel-image-optimizer
It can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools.
It can optimize an image by automatically finding out the mime type and best optimizer.
use ImageOptimizer;ImageOptimizer::optimize($pathToImage, $pathToOptimizedImage);
For more customization follw: https://github.com/spatie/laravel-image-optimizer
Next, we will add an extra step that is not provided in the Spatie’s compressor. This will help us reduce the image size even further.
We are going to use the convert tool by ImageMagick. Setting quality over 65 in the convert tool, can be an overkill.
public function convert($from, $to)
{
$command = 'convert '
. $from
.' '
. '-sampling-factor 4:2:0 -strip -quality 65'
.' '
. $to;
return `$command`;
}
Let’s call convert, on the optimized image.
ImageOptimizer::optimize($pathToImage, $pathToOptimizedImage);
$this->convert($pathToOptimizedImage, $pathToOptimizedImage);
Labels: Laravel, Web development