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
Laravel 9 Phone Number Validation Using Regex
Laravel 9 Phone Number Validat...

In this article, we will see laravel 9 phone number validation using regex. In laravel 9 we will see different meth...

Read More


How to Disable Right Click using jQuery
How to Disable Right Click usi...

In this small post i will show you how to disable right click using jquery. Here, we will disable right click on pa...

Read More


Laravel 8 Inner Join Query Example
Laravel 8 Inner Join Query Exa...

In this tutorial we will learn about laravel 8 inner join query example. Also see how to join two tables in laravel 8. I...

Read More


Laravel AJAX CRUD example
Laravel AJAX CRUD example

Today I will show you how to create ajax crud operations in laravel. In laravel 6/7 ajax crud operation, we can perform...

Read More