Image Optimization With Spatie Laravel Image Optimizer

Published on by

Image Optimization With Spatie Laravel Image Optimizer image

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();
 
$optimizerChain->optimize($pathToImage);

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" \
--require="spatie/image-optimizer:1.*"
 
composer install
 
brew install \
jpegoptim \
optipng \
pngquant \
svgo \
gifsicle

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";
exit(1);
}
 
// Get the image and store the original size
$image = $argv[1];
$originalSize = filesize($image);
 
// Optimize updates the existing image
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($image);
 
// Clear stat cache to get the optimized size
clearstatcache();
 
// Check the optimized size
$optimizedSize = filesize($image);
$percentChange = (1 - $optimizedSize / $originalSize) * 100;
echo sprintf("The image is now %.2f%% smaller\n", $percentChange);
exit(0);

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')
->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.

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:

<br></br><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.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Basset is an alternative way to load CSS & JS assets image

Basset is an alternative way to load CSS & JS assets

Read article
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article