Blog Detail

09

Nov
Image-optimizer - Easily Optimize Images Using PHP cover image

arrow_back Image-optimizer - Easily Optimize Images Using PHP

Images are crucial to ensuring that your content is more accessible, attractive, and engaging to users, but they’re equally important in terms of SEO. Optimization of your images helps to ensure a better user experience and that meets users’ expectations. Image optimization is the process of creating and delivering high-quality images in the ideal format, size, and resolution to increase user engagement.

Image-optimizer is a package released by Spatie that can optimize PNGs, JPGs, SVGs, and GIFs by running them through a chain of various image optimization tools. This package will automatically detect which optimization binaries are installed on your system and use them.

How to Install?

You can install the package via composer:

composer require spatie/image-optimizer

Usage

This is the default way to use the package:

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.
To keep the original image, you can pass through a second argument optimize:

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.

Optimization tools

The package will use these optimizers if they are present on your system:

  • JpegOptim
  • Optipng
  • Pngquant 2
  • SVGO 1
  • Gifsicle
  • cwebp

Which tools will do what?

The package will automatically decide which tools to use on a particular image.

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.

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, progressively scanned image.
  • -o2: this set the optimization level to two (multiple IDAT compression trials)

SVGs

SVGs will be minified by SVGO 1. 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. Please be aware that SVGO can break your SVG.

For now, the default configuration used for SVGO is only compatible with SVGO 1.x To use options compatible with SVGO 2.x, you need to create your own optimization chain.

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

WEBPs

WEBPs will be optimized by Cwebp. These options will be used:

  • -m 6 for the slowest compression method to get the best compression.
  • -pass 10 for maximizing the amount of analysis pass.
  • -mt multithreading for some speed improvements.
  • -q 90 Quality factor that brings the least noticeable changes

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

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.
You can easily add your optimizer by using the addOptimizer method on an OptimizerChain.

use Spatie\ImageOptimizer\ImageOptimizerFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain
   ->addOptimizer(new YourCustomOptimizer())
   ->optimize($pathToImage);

You can view more details on Github.

Published at : 09-11-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project