Easily optimize images using PHP
, (*1)
This package can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools. Here's how you can use it:, (*2)
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($pathToImage);
The image at $pathToImage
will be overwritten by an optimized version which should be smaller. The package will automatically detect which optimization binaries are installed on your system and use them., (*3)
Here are some example conversions that have been done by this package., (*4)
Loving Laravel? Then head over to the Laravel specific integration., (*5)
Using WordPress? Then try out the WP CLI command., (*6)
Installation
You can install the package via composer:, (*7)
composer require spatie/image-optimizer
The package will use these optimizers if they are present on your system:, (*8)
Here's how to install all the optimizers on Ubuntu:, (*9)
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
And here's how to install the binaries on MacOS (using Homebrew):, (*10)
brew install jpegoptim
brew install optipng
brew install pngquant
brew install svgo
brew install gifsicle
The package will automatically decide which tools to use on a particular image., (*11)
JPGs
JPGs will be made smaller by running them through JpegOptim. These options are used:
- -m85
: this will store the image with 85% quality. This setting seems to satisfy Google's Pagespeed compression rules
- --strip-all
: this strips out all text information such as comments and EXIF data
- --all-progressive
: this will make sure the resulting image is a progressive one, meaning it can be downloaded using multiple passes of progressively higher details., (*12)
PNGs
PNGs will be made smaller by running them through two tools. The first one is Pngquant 2, a lossy PNG compressor. We set no extra options, their defaults are used. After that we run the image through a second one: Optipng. These options are used:
- -i0
: this will result in a non-interlaced, progressive scanned image
- -o2
: this set the optimization level to two (multiple IDAT compression trials), (*13)
SVGs
SVGs will be minified by SVGO. SVGO's default configuration will be used, with the omission of the cleanupIDs
plugin because that one is known to cause troubles when displaying multiple optimized SVGs on one page., (*14)
Please be aware that SVGO can break your svg. You'll find more info on that in this excellent blogpost by Sara Soueidan., (*15)
GIFs
GIFs will be optimized by Gifsicle. These options will be used:
- -O3
: this sets the optimization level to Gifsicle's maximum, which produces the slowest but best results, (*16)
Usage
This is the default way to use the package:, (*17)
``` php
use Spatie\ImageOptimizer\OptimizerChainFactory;, (*18)
$optimizerChain = OptimizerChainFactory::create();, (*19)
$optimizerChain->optimize($pathToImage);, (*20)
The image at `$pathToImage` will be overwritten by an optimized version which should be smaller.
The package will automatically detect which optimization binaries are installed on your system and use them.
To keep the original image, you can pass through a second argument`optimize`:
```php
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($pathToImage, $pathToOutput);
In that example the package won't touch $pathToImage
and write an optimized version to $pathToOutput
., (*21)
Setting a timeout
You can set the maximum of time in seconds that each individual optimizer in a chain can use by calling setTimeout
:, (*22)
$optimizerChain
->setTimeout(10)
->optimize($pathToImage);
In this example each optimizer in the chain will get a maximum 10 seconds to do it's job., (*23)
Creating your own optimization chains
If you want to customize the chain of optimizers you can do so by adding Optimizer
s manually to an OptimizerChain
., (*24)
Here's an example where we only want optipng
and jpegoptim
to be used:, (*25)
use Spatie\ImageOptimizer\OptimizerChain;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
$optimizerChain = (new OptimizerChain)
->addOptimizer(new Jpegoptim([
'--strip-all',
'--all-progressive',
]))
->addOptimizer(new Pngquant([
'--force',
]))
Notice that you can pass the options an Optimizer
should use to its constructor., (*26)
Writing a custom optimizers
Want to use another command line utility to optimize your images? No problem. Just write your own optimizer. An optimizer is any class that implements the Spatie\ImageOptimizer\Optimizers\Optimizer
interface:, (*27)
namespace Spatie\ImageOptimizer\Optimizers;
use Spatie\ImageOptimizer\Image;
interface Optimizer
{
/**
* Returns the name of the binary to be executed.
*
* @return string
*/
public function binaryName(): string;
/**
* Determines if the given image can be handled by the optimizer.
*
* @param \Spatie\ImageOptimizer\Image $image
*
* @return bool
*/
public function canHandle(Image $image): bool;
/**
* Set the path to the image that should be optimized.
*
* @param string $imagePath
*
* @return $this
*/
public function setImagePath(string $imagePath);
/**
* Set the options the optimizer should use.
*
* @param array $options
*
* @return $this
*/
public function setOptions(array $options = []);
/**
* Get the command that should be executed.
*
* @return string
*/
public function getCommand(): string;
}
If you want to view an example implementation take a look at the existing optimizers shipped with this package., (*28)
You can easily add your optimizer by using the addOptimizer
method on an OptimizerChain
., (*29)
``` php
use Spatie\ImageOptimizer\ImageOptimizerFactory;, (*30)
$optimizerChain = OptimizerChainFactory::create();, (*31)
$optimizerChain
->addOptimizer(new YourCustomOptimizer())
->optimize($pathToImage);, (*32)
## Logging the optimization process
By default the package will not throw any errors and just operate silently. To verify what the package is doing you can set a logger:
```php
use Spatie\ImageOptimizer\OptimizerChainFactory;
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain
->useLogger(new MyLogger())
->optimize($pathToImage);
A logger is a class that implements Psr\Log\LoggerInterface
. A good logging library that's fully compliant is Monolog. The package will write the to log which Optimizers
are used, which commands are executed and their output., (*33)
Example conversions
Here are some real life example conversions done by this package., (*34)
png
Original: Photoshop 'Save for web' | PNG-24 with transparency
40 Kb, (*35)
, (*36)
Optimized
16 Kb (40%), (*37)
, (*38)
jpg
Original: Photoshop 'Save for web' | quality 60, optimized
547 Kb, (*39)
, (*40)
Optimized
525 Kb (95%), (*41)
, (*42)
credits: Jeff Sheldon, via Unsplash, (*43)
svg
Original: Illustrator | Web optimized SVG export
26 Kb, (*44)
, (*45)
Optimized
20 Kb (76%), (*46)
, (*47)
Changelog
Please see CHANGELOG for more information what has changed recently., (*48)
Testing
bash
composer test
, (*49)
Contributing
Please see CONTRIBUTING for details., (*50)
Security
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker., (*51)
Postcardware
You're free to use this package (it's MIT-licensed), but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using., (*52)
Our address is: Spatie, Samberstraat 69D, 2060 Antwerp, Belgium., (*53)
We publish all received postcards on our company website., (*54)
Credits
This package has been inspired by psliwa/image-optimizer, (*55)
Emotional support provided by Joke Forment, (*56)
Support us
Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website., (*57)
Does your business depend on our contributions? Reach out and support us on Patreon.
All pledges will be dedicated to allocating workforce on maintenance and new awesome stuff., (*58)
License
The MIT License (MIT). Please see License File for more information., (*59)