Image Optimization With Spatie Laravel Image Optimizer


July 24th, 2017


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.

Enter Spatie’s image-optimizer PHP package:

This package can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools.

To go along with this tool (wait for it), they’ve released a package for Laravel integration which makes it simple to use in a Laravel application.

We will cover a basic overview and some examples in action with a Laravel application.

Image Optimization Basics

One implicit goal most people have when using an image optimization tool is to provide smaller images yet sacrificing as little quality as possible. While striking a balance between smaller images and crisp quality is different for everybody, most people want their images to still look good. Optimization tools are available for every image format, and do a great job of optimizing without compromising the images; however, finding a unified API that connects these tools is where Spatie’s package fills an important void.

According to the authors of the plugin, Spatie’s image-optimizer package provides the glue code that developers might ignore or be overwhelmed with:

You must make sure that you pass the right kind of image to the right optimizer. You also have to decide which optimization parameters you’re going to use for each tool. None of this is rocket science, but I bet that the vast majority of small to medium sites don’t bother writing this code or researching these optimizations.

The interface for Spatie’s image-optimizer package is quite simple:

1use Spatie\ImageOptimizer\OptimizerChainFactory;
3$optimizerChain = OptimizerChainFactory::create();

Internally, the package uses the following optimizers if they are available on the system to optimize images:

Quick Example

Let’s create a small CLI project and run an image optimization to get a feel for the package. Later we will take the Laravel package for a spin to see how easy the package makes optimizing images.

If you want to follow along, check out the readme for installation instructions for the optimization tools.

First, create a small project somewhere on your filesystem:

1mkdir ~/Code/image-optimizer-example && cd $_
3composer init --no-interaction \
4--name="laravel-news/image-optimizer-example" \
7composer install
9brew install \
10 jpegoptim \
11 optipng \
12 pngquant \
13 svgo \
14 gifsicle

Create an index.php file with the following:

1require __DIR__.'/vendor/autoload.php';
3use Spatie\ImageOptimizer\OptimizerChainFactory;
5if (!isset($argv[1]) || !file_exists($argv[1])) {
6 echo "Please provide a valid image path";
7 exit(1);
10// Get the image and store the original size
11$image = $argv[1];
12$originalSize = filesize($image);
14// Optimize updates the existing image
15$optimizerChain = OptimizerChainFactory::create();
18// Clear stat cache to get the optimized size
21// Check the optimized size
22$optimizedSize = filesize($image);
23$percentChange = (1 - $optimizedSize / $originalSize) * 100;
24echo sprintf("The image is now %.2f%% smaller\n", $percentChange);

Most of the code was validating the argument and getting the file size. It only took a few lines of code from the library in order to optimize the image.

If you run it against a file, you should see some savings (unless the file you picked was already optimized). I used a Creative-Commons photo of the Alexandra Bridge to run the script:

1php index.php ./6873422757_91470bca43_o.jpg
2The image is now 15.23% smaller

Awesome, that was easy! Now that we’ve looked at a basic script, let’s get the package working with a Laravel application!

A Laravel Example

Let’s work on a quick example of using Spatie’s laravel-image-optimizer package within Laravel. First, create a project somewhere:

1laravel new image-optimizer
2cd ./laravel-image-optimizer
3valet link # use this if you are using Laravel valet
4composer require spatie/laravel-image-optimizer
5php artisan make:controller PhotosController

The commands create a new Laravel application, link Laravel Valet (skip if you are not using Valet), and create a PhotosController for our demo.

Next, follow the installation guide to set up the laravel-image-optimizer package provider, facade, and middleware. Once Laravel 5.5 ships, the package auto-discovery feature will reduce setup even more.

After setting up the provider and middleware, add the following route in the routes/web.php file:

1Route::post('/photos', 'PhotosController@store')
2 ->middleware('optimizeImages');

The route uses Spatie’s image optimization middleware to automatically optimize uploaded images.

Next, the PhotosController will store the optimized image and respond with an “OK” message just for testing.

1namespace App\Http\Controllers;
3class PhotosController extends Controller {
4 public function store() {
5 $this->validate(request(), [
6 'photo' => 'required|image:jpeg '
7 ]);
9 request()->photo->storeAs('images', 'optimized.jpg');
11 return response('OK', 201);
12 }

Lastly, create a simple form using the existing welcome.blade.php file you can use to submit an image:

1<br></br><form action="/photos" enctype="multipart/form-data" method="POST">
2 {{ csrf_field() }}
3 <div class="form-group">
4 <label for="">Photo</label>
5 <input class="form-control" name="photo" type="file" />
6 <button type="submit">Upload</button>
7 </div>

That should be enough to submit a JPEG by visiting the / route of the application and uploading a JPEG file. If you hooked up the service provider and the middleware, you should see that the file located at storage/app/images/optimized.jpg is a reduced size from the original you submitted.

With hardly any effort, you will benefit from optimized images that use this middleware! You can also reach for the ImageOptimizer facade or the OptimizerChain service to optimize images using the same API from the base image-optimizer package.

The package also allows you to write your own custom optimizations and tweak the default options in the Laravel package’s configuration file. The installation section provides instructions on how to publish the config file.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners