Image Optimization With Spatie Laravel Image Optimizer
Laravel Tutorials / updated: July 24, 2017

Image Optimization With Spatie Laravel Image Optimizer

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:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$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:

mkdir ~/Code/image-optimizer-example && cd $_

composer init --no-interaction \
--name="laravel-news/image-optimizer-example" \

composer install

brew install \
  jpegoptim \
  optipng \
  pngquant \
  svgo \

Create an index.php file with the following:

require __DIR__.'/vendor/autoload.php';

use Spatie\ImageOptimizer\OptimizerChainFactory;

if (!isset($argv[1]) || !file_exists($argv[1])) {
    echo "Please provide a valid image path";

// Get the image and store the original size
$image = $argv[1];
$originalSize = filesize($image);

// Optimize updates the existing image
$optimizerChain = OptimizerChainFactory::create();

// Clear stat cache to get the optimized size

// Check the optimized size
$optimizedSize = filesize($image);
$percentChange = (1 - $optimizedSize / $originalSize) * 100;
echo 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:

php index.php ./6873422757_91470bca43_o.jpg
The 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:

laravel new image-optimizer
cd ./laravel-image-optimizer
valet link # use this if you are using Laravel valet
composer require spatie/laravel-image-optimizer
php 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:

Route::post('/photos', 'PhotosController@store')

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.

namespace App\Http\Controllers;

class PhotosController extends Controller {
    public function store() {
        $this->validate(request(), [
            'photo' => 'required|image:jpeg '

        request()->photo->storeAs('images', 'optimized.jpg');

        return response('OK', 201);

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

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

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.

Laravel News Partners


Join the weekly newsletter and never miss out on new tips, tutorials, and more.