spatie/laravel-image-optimizer

repository·main·Indexed 23 days ago

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

A Laravel integration for the spatie/image-optimizer package that enables automatic or manual optimization of PNG, JPG, SVG, and GIF images using system binaries. It provides an ImageOptimizer facade, an OptimizerChain class, and OptimizeImages middleware to automatically optimize uploaded images in HTTP requests.

Tokens
1.7K
Snippets
5
Records
11
Agent score
78%

What's inside spatie/laravel-image-optimizer

  1. Automatically optimize uploaded images with middleware

    main

    You can automatically optimize all images included in a request by applying the optimizeImages middleware to your routes.

    First, register the middleware alias in your HTTP Kernel:

    // app/Http/Kernel.php
    protected $middlewareAliases = [
       ...
       'optimizeImages' => \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class,
    ];

    Then, apply it to your routes:

    Route::middleware('optimizeImages')->group(function () {
        // All images in requests to these routes will be optimized automatically
        Route::post('upload-images', 'UploadController@index');
    });
    Route::middleware('optimizeImages')->group(function () {
        // all images will be optimized automatically
        Route::post('upload-images', 'UploadController@index');
    });
  2. Install spatie/laravel-image-optimizer via Composer

    main

    Install the package using composer to integrate image optimization into your Laravel application. Note that this package requires various optimization binaries (like jpegoptim, optipng, etc.) to be installed on your system. You can find details on which binaries are supported and how to install them in the spatie/image-optimizer repository.

    composer require spatie/laravel-image-optimizer
  3. Publish the image optimizer configuration

    main

    To customize the default optimizers, their CLI arguments, timeouts, or logging behavior, publish the configuration file to your config directory using the following command:

    php artisan vendor:publish --provider="Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider"
  4. Configure optimizer arguments in config/image-optimizer.php

    main

    The configuration file allows you to pass specific CLI flags to each optimizer. Each optimizer is identified by its fully qualified class name.

    Key configuration options include:

    • optimizers: An associative array where keys are optimizer classes (e.g., Jpegoptim::class) and values are arrays of CLI arguments.
    • timeout: The maximum time in seconds each optimizer is allowed to run separately.
    • log_optimizer_activity: Set to true to append optimizer output to the default log, or provide a Psr\Log\LoggerInterface instance.
    use Spatie\ImageOptimizer\Optimizers\Svgo;
    use Spatie\ImageOptimizer\Optimizers\Optipng;
    use Spatie\ImageOptimizer\Optimizers\Gifsicle;
    use Spatie\ImageOptimizer\Optimizers\Pngquant;
    use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
    use Spatie\ImageOptimizer\Optimizers\Cwebp;
    
    return [
        'optimizers' => [
    
            Jpegoptim::class => [
                '-m85',
                '--strip-all',
                '--all-progressive'
            ],
    
            Pngquant::class => [
                '--force'
            ],
    
            Optipng::class => [
                '-i0',
                '-o2',
                '-quiet'
            ],
    
            Svgo::class => [
                '--disable=cleanupIDs'
            ],
    
            Gifsicle::class => [
                '-b',
                '-O3'
            ],
            
            Cwebp::class => [
                '-m 6',
                '-pass 10',
                '-mt',
                '-q 90',
            ],
        ],
    
        'timeout' => 60,
    
        'log_optimizer_activity' => false,
    ];
  5. Optimize images using the ImageOptimizer facade

    main

    The easiest way to optimize images is via the ImageOptimizer facade. You can either replace the original file with an optimized version or save the result to a new path.

    use ImageOptimizer;
    
    // The image will be replaced with an optimized version which should be smaller
    ImageOptimizer::optimize($pathToImage);
    
    // If you use a second parameter, the package will not modify the original
    ImageOptimizer::optimize($pathToImage, $pathToOptimizedImage);
  6. Use the OptimizeImages middleware to automatically optimize uploads

    main

    The Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages middleware automatically intercepts incoming HTTP requests, identifies all uploaded files, and runs them through the OptimizerChain before the request reaches your application logic.

    This is useful for ensuring that any image uploaded via a form is optimized immediately upon arrival. The middleware filters for valid UploadedFile instances and calls $optimizerChain->optimize() on their file paths. Note that in a testing environment, the middleware skips the validity check and attempts to optimize all files.