How to Reduce Image File Size in Laravel 12 Using Spatie?

How to Reduce Image File Size in Laravel 12 Using Spatie

In this article, we will go over optimizing and compressing images with the Spatie Image package in Laravel 12.

Large images will slow down your website and increase your bandwidth costs; however, if you properly optimize them prior to saving them, you can increase your page speed and overall performance.

We will be using the Composer package spatie/image. This is an excellent choice when working with images in PHP. It has features such as resizing, cropping, converting, and optimizing images. You will only need a small amount of code to do so. It can read and write standard image formats including JPEG, PNG, GIF, WebP and AVIF. It works seamlessly with any Laravel application.

Laravel Development Services

Once this tutorial is complete, you will have a working image upload system that automatically compresses the images before saving them.

What We Will Build

In this example, we will:

  • Install Laravel 12
  • Install the Spatie Image package
  • Configure system optimizers
  • Create upload routes
  • Build a controller for image processing
  • Create a simple upload form
  • Optimize images automatically

Steps to Compress Images in Laravel 12

Step 1: Install Laravel 12

If you already have a Laravel project, you can skip this step.

Otherwise, create a new Laravel application using:

composer create-project laravel/laravel image-compressor

Move into your project directory:

cd image-compressor

Step 2: Install Spatie Image Package

Now, install the Spatie Image package using Composer:

composer require spatie/image

Install Image Optimization Tools

Spatie uses system tools to optimize images. You must install them depending on your OS.

For 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

For macOS

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

For Fedora / CentOS / RHEL

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

They allow you to decrease the file size significantly but still keep the image quality as good as possible.

Step 3: Create Routes

Open the routes file: routes/web.php

Add the following routes:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;
Route::get('/upload-image', [ImageController::class, 'index']);
Route::post('/upload-image', [ImageController::class, 'store'])
    ->name('image.upload');
  • GET → Displays upload form
  • POST → Handles image upload and compression

Step 4: Create Image Controller

Generate a controller using Artisan:

php artisan make:controller ImageController

Now open:

app/Http/Controllers/ImageController.php

Replace the content with:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Spatie\Image\Image;

class ImageController extends Controller
{
    /**
     * Show upload form
     */
    public function index(): View
    {
        return view('upload-image');
    }

    /**
     * Store and optimize image
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|max:2048',
        ]);

        $imageName = time() . '.' . $request->image->extension();

        Image::load($request->image->path())
            ->optimize()
            ->save(public_path('uploads/' . $imageName));

        return back()
            ->with('success', 'Image uploaded and optimized successfully.')
            ->with('image', $imageName);
    }
}

Create Upload Directory

Create a folder inside public:

mkdir public/uploads

This is where optimized images will be stored.

Step 5: Create Upload View File

Now, create the Blade file:

resources/views/upload-image.blade.php

Add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 12 Image Compression</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

<div class="container mt-5">

    <div class="card">

        <div class="card-header bg-primary text-white">
            <h4>Laravel 12 Image Optimization</h4>
        </div>

        <div class="card-body">

            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @if (session('success'))
                <div class="alert alert-success">
                    {{ session('success') }}
                </div>

                <img src="/uploads/{{ session('image') }}"
                     class="img-fluid mt-3"
                     style="max-width:300px;">
            @endif

            <form method="POST"
                  action="{{ route('image.upload') }}"
                  enctype="multipart/form-data">

                @csrf

                <div class="mb-3">
                    <label class="form-label">Select Image</label>

                    <input type="file"
                           name="image"
                           class="form-control">
                </div>

                <button class="btn btn-success">
                    Upload & Compress
                </button>

            </form>

        </div>

    </div>

</div>

</body>
</html>

Step 6: Run Laravel Application

Start the Laravel server:

php artisan serve

Now open your browser and visit:

http://localhost:8000/upload-image 

You will see an image upload form.

Upload any image, and Laravel will automatically:

  • Optimization
  • Reduces the size of the uploaded image
  • Saves in the public/uploads directory
  • Displays the resulting image

How Image Optimization Works

When you upload an image, this code runs:

Image::load($request->image->path())
    ->optimize()
    ->save(...);

This does the following:

  • Loads the uploaded image
  • Runs system optimizers
  • Compresses the file
  • Saves optimized output

No quality loss is visible in most cases.

Benefits of Using Spatie Image

Using this approach gives you:

  • Your website will load faster.
  • Less storage space is required on your server.
  • You will use less bandwidth.
  • Your search engine optimization will improve.
  • The user experience on your site will be improved.

Optional: Resize + Optimize (Advanced)

You can also resize images before saving:

Image::load($request->image->path())
    ->width(800)
    ->height(600)
    ->optimize()
    ->save(public_path('uploads/' . $imageName));

This resizes and compresses the image together.

Conclusion

In this blog, you learned how to compress and optimize images in Laravel 12 using the Spatie Image package. If you are developing a Laravel application where users upload content, images of products, and media for blogs, you should keep image optimization as one of your development tasks.

Hire laravel Developer

FAQ

1. What is Spatie Image Optimizer?

The Spatie image optimizer is a Laravel-based package that will automatically optimize and compress an image using various optimization programs with very little effect on the overall quality or detail of the image.

2. Does the optimization of images result in any loss of quality?

No, the optimization of images is done using lossless and/or minimal-loss compression, so very little residual quality will be detected after the compression and/or optimization.

3. Is this package compatible with Laravel 12?

Yes, the Spatie image optimizer package supports Laravel 12 as long as the PHP version meets the minimum specifications.

Previous Article

How JavaScript Quietly Became the Infrastructure of the Web

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨