spatie/image-optimizer

repository·main·Indexed 25 days ago

https://github.com/spatie/image-optimizer

A PHP package that optimizes PNG, JPG, SVG, GIF, WEBP, and AVIF images by orchestrating a chain of system-level binaries such as jpegoptim, optipng, pngquant, svgo, gifsicle, cwebp, and avifenc. It provides an OptimizerChainFactory for automatic binary detection and an OptimizerChain for custom optimization pipelines, supporting both in-place optimization and output to a separate path.

Tokens
3K
Snippets
10
Records
21
Agent score
84%

What's inside spatie/image-optimizer

  1. Install required optimization binaries

    main

    The package requires specific system binaries to perform optimizations. Depending on your operating system, install the necessary tools using the following commands:

    Ubuntu/Debian

    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
    sudo apt-get install webp
    sudo apt-get install libavif-bin # minimum 0.9.3

    MacOS (Homebrew)

    brew install jpegoptim
    brew install optipng
    brew install pngquant
    npm install -g svgo
    brew install gifsicle
    brew install webp
    brew install libavif

    Fedora/RHEL/CentOS

    sudo dnf install epel-release
    sudo dnf install jpegoptim
    sudo dnf install optipng
    sudo dnf install pngquant
    sudo npm install -g svgo
    sudo dnf install gifsicle
    sudo dnf install libwebp-tools
    sudo dnf install libavif-tools
  2. Optimize images with the default OptimizerChain

    main

    The simplest way to use the package is to create an optimizer chain using OptimizerChainFactory. By default, the package will automatically detect which optimization binaries are installed on your system and use them. Calling optimize($pathToImage) will overwrite the original file with an optimized version.

    use Spatie\
    ImageOptimizer\OptimizerChainFactory;
    
    $optimizerChain = OptimizerChainFactory::create();
    
    $optimizerChain->optimize($pathToImage);
  3. Optimize images using OptimizerChainFactory

    main

    Use OptimizerChainFactory::create() to generate an optimizer chain. The optimize() method takes a path to an image and overwrites the file with an optimized version. The package automatically detects which optimization binaries are installed on your system and uses them for the appropriate file types (PNG, JPG, WEBP, AVIF, SVG, GIF).

    use Spatie\
    ImageOptimizer\
    OptimizerChainFactory;
    
    $optimizerChain = OptimizerChainFactory::create();
    
    $optimizerChain->optimize($pathToImage);
  4. Optimize images without overwriting the original

    main

    To preserve the original image, pass a second argument to the optimize method representing the destination path. The package will write the optimized version to the output path instead of modifying the source.

    use Spatie\ImageOptimizer\OptimizerChainFactory;
    
    $optimizerChain = OptimizerChainFactory::create();
    
    $optimizerChain->optimize($pathToImage, $pathToOutput);
  5. Create a custom optimization chain

    main

    You can manually build a chain with specific optimizers by instantiating OptimizerChain and using addOptimizer(). You can pass specific CLI options to the optimizer's constructor.

    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',
       ]))
  6. Handle optimizer errors and failures

    main

    By default, if an optimizer fails (e.g., a binary exits with a non-zero status), the failure is logged and the chain continues. You can change this behavior using throws():

    • $optimizerChain->throws(): Rethrows the failure and stops the entire chain.
    • $optimizerChain->throws(false): Explicitly maintains the default 'log and continue' behavior.
    • $optimizerChain->throws(callable): Pass a callback to decide whether to continue or abort. The callback receives (Throwable $exception, Optimizer $optimizer, Image $image).
    use Spatie\ImageOptimizer\Image;
    use Spatie\ImageOptimizer\Optimizer;
    
    $optimizerChain
        ->throws(function (Throwable $exception, Optimizer $optimizer, Image $image) {
            report($exception);
    
            // return to continue the chain, or throw to abort it
        })
        ->optimize($pathToImage);
  7. Implement a custom binary-based optimizer

    main
    To use a new command-line utility, implement the Spatie\ImageOptimizer\Optimizers\Optimizer interface. You must define the binaryName(), canHandle(Image $image), setImagePath(), setOptions(), and getCommand() methods.
  8. Implement a self-handling optimizer (e.g., for APIs)

    main

    If your optimizer does not use a shell command (for example, it calls an external API), implement Spatie\ImageOptimizer\SelfHandlingOptimizer. The easiest way is to extend Spatie\ImageOptimizer\Optimizers\BaseSelfHandlingOptimizer and implement canHandle(Image $image) and handle(Image $image, LoggerInterface $logger). Inside handle, you are responsible for writing the optimized bytes back to the image path.

    use Psr\Log\LoggerInterface;
    use Spatie\ImageOptimizer\Image;
    use Spatie\ImageOptimizer\Optimizers\BaseSelfHandlingOptimizer;
    
    class ApiOptimizer extends BaseSelfHandlingOptimizer
    {
        public function canHandle(Image $image): bool
        {
            return $image->mime() === 'image/jpeg';
        }
    
        public function handle(Image $image, LoggerInterface $logger): void
        {
            // Optimize $image->path() however you like, e.g. by calling an API,
            // and write the optimized bytes back to that path. Throw on failure.
        }
    }
  9. Log the optimization process

    main

    To see which optimizers are being used and view their command output, provide a logger that implements Psr\Log\LoggerInterface using the useLogger method.

    use Spatie\ImageOptimizer\OptimizerChainFactory;
    
    $optimizerChain = OptimizerChainFactory::create();
    
    $optimizerChain
       ->useLogger(new MyLogger())
       ->optimize($pathToImage);
  10. Configure SVGO via svgo.config.js

    main

    The image-optimizer package uses SVGO for SVG optimization. You can customize the optimization behavior by providing a svgo.config.js file in your project root. The configuration uses the plugins array to define optimization presets and overrides.

    Commonly, the preset-default plugin is used with specific overrides to prevent loss of critical SVG attributes like viewBox or ids.

    module.exports = {
      plugins: [
        {
          name: 'preset-default',
          params: {
            overrides: {
              cleanupIDs: false,
              removeViewBox: false,
            },
          },
        },
      ],
    };