How To Image Optimization In Laravel 9 Using Spatie

Websolutionstuff | Feb-10-2023 | Categories : Laravel

In this article, we will see how to image optimization in laravel 9 using spatie. Here, we will learn about image optimization in laravel 8 and laravel 9. Here will use spatie/image-optimizer package to optimize the image. It can easily optimize the image.

This package can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools.

So, let's see laravel 9 image compression, how to optimize images in laravel 9, laravel 9 image resize, laravel 9 image optimizer, and image optimizer laravel 8.

 Step 1: Install Laravel 9

In this step, we will install laravel 9 using the following command.

composer create-project laravel/laravel laravel-9-image-optimization


Step 2: Install spatie/image-optimizer Package

Now, we will install the image optimizer package using the composer command.

composer require spatie/image-optimizer

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



Step 3: Publish Package

In this step, we will publish the package using the following command.

php artisan vendor:publish --provider="Spatie\LaravelImageOptimizer\ImageOptimizerServiceProvider"

After running the above command, it can generate an image-optimizer.php file.



use Spatie\ImageOptimizer\Optimizers\Cwebp;
use Spatie\ImageOptimizer\Optimizers\Gifsicle;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
use Spatie\ImageOptimizer\Optimizers\Optipng;
use Spatie\ImageOptimizer\Optimizers\Pngquant;
use Spatie\ImageOptimizer\Optimizers\Svgo;

return [
     * When calling `optimize` the package will automatically determine which optimizers
     * should run for the given image.
    'optimizers' => [

        Jpegoptim::class => [
            '-m85', // set maximum quality to 85%
            '--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

        Pngquant::class => [
            '--force', // required parameter for this package

        Optipng::class => [
            '-i0', // this will result in a non-interlaced, progressive scanned image
            '-o2',  // this set the optimization level to two (multiple IDAT compression trials)
            '-quiet', // required parameter for this package

        Svgo::class => [
            '--disable=cleanupIDs', // disabling because it is know to cause troubles

        Gifsicle::class => [
            '-b', // required parameter for this package
            '-O3', // this produces the slowest but best results

        Cwebp::class => [
            '-m 6', // for the slowest compression method in order 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.

    * The directory where your binaries are stored.
    * Only use this when you binaries are not accessible in the global environment.
    'binary_path' => '',

     * The maximum time in seconds each optimizer is allowed to run separately.
    'timeout' => 60,

     * If set to `true` all output of the optimizer binaries will be appended to the default log.
     * You can also set this to a class that implements `Psr\Log\LoggerInterface`.
    'log_optimizer_activity' => false,


Step 4: Create Routes

In this step, we will create routes in the web.php file.



use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageOptimizationController;

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
Route::get('/optimize', [ImageOptimizationController::class, 'index']);
Route::get('/optimize/images', [ImageOptimizationController::class, 'store'])->middleware('optimizeImages');


Step 5: Create Controller

Now, we will create ImageOptimizatioController using the following command.

php artisan make:controller ImageOptimizationController



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Session;

class ImageOptimizationController extends Controller
    public function index(){
        return view('image-optimize');

    public function store() {
        $this->validate(request(), [
            'image' => 'required|image:jpeg '

        request()->image->storeAs('images', 'optimized-img.jpg');

        Session::put('success', 'Image has been successfully optimize');

        return redirect()->back();



Step 7: Add Middleware

Spatie package provides its own middleware for image optimization. add middleware in the kernel.php.


protected $routeMiddleware = [
        'optimizeImages' => \Spatie\LaravelImageOptimizer\Middlewares\OptimizeImages::class,


Step 8: Create Blade File

Now, we will create an image-optimizer.blade.php file. So, add the following HTML code to that file.


<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="" rel="stylesheet">
    <body class="antialiased">
        <div class="container">
            <div class="panel-body"> 
                <div class="col-md-8">    
                    <h5 style="margin-top: 50px;margin-bottom:30px;">How To Image Optimization In Laravel 9 Using Spatie - Websolutionstuff</h5>
                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                    {{ Session::flush(); }}
                @if (count($errors) > 0)
                    <div class="alert alert-danger">
                        <strong>Whoops!</strong> There were some problems with your input.
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                <form action="/optimize/images" method="POST" enctype="multipart/form-data">
                    <div class="row"> <br>   
                        <div class="col-md-6">
                            <input type="file" name="image" class="form-control">
                        <div class="col-md-6">
                            <button type="submit" class="btn btn-success">Upload</button>


Step 9: Run Laravel 9 Application

Now, we will run the laravel 9 image optimizer application using the following command.

php artisan serve


image optimization in laravel 9 using spatie


You might also like:

Recommended Post
Featured Post
How To Block IP Address In Laravel 10
How To Block IP Address In Lar...

In this article, we will see how to block IP addresses in laravel 10. Here we will learn about how to restrict...

Read More


How To Send E-mail Using Queue In Laravel 9
How To Send E-mail Using Queue...

In this tutorial, I will show you how to send e-mail using queue in laravel 9, Some time we can see many...

Read More


Laravel 9 Generate PDF File Using DomPDF
Laravel 9 Generate PDF File Us...

In this tutorial, we will see laravel 9 generate pdf file using dompdf. For generating pdf files we will use the la...

Read More


What Is New In Laravel 9 - Features Of Laravel 9
What Is New In Laravel 9 - Fea...

In this article, we will see what is new in laravel 9 and the features of laravel 9. Laravel 9 is recently released...

Read More