Logo

How to Compress Image Size in Laravel 11 Using Spatie/Image?

How to Compress Image Size in Laravel 11 Using Spatie/Image?

How to Compress Image Size in Laravel 11 Using Spatie/Image?

In this article, I will guide you through optimizing images in a Laravel 11 application using the Spatie/Image package. Image optimization is crucial for web applications to ensure faster load times, reduce bandwidth usage, and enhance overall user experience.

Steps to Optimize Image Size in Laravel 11

Step 1 : Set Up Your Laravel 11 Application

If you haven’t already set up a Laravel 11 project, you can do so with the following command:

				
					composer create-project laravel/laravel example-app

				
			

Step 2 : Install Spatie/Image Package

Next, install the Spatie/Image package via Composer. Open your terminal and run:

				
					composer require spatie/image

				
			

Additionally, you’ll need to install some image optimization tools on your server. These tools work in conjunction with the Spatie/Image package to compress and optimize images. Here’s how you can install them:

For Ubuntu/Debian :

				
					sudo apt-get install jpegoptim optipng pngquant gifsicle webp libavif-bin
sudo npm install -g svgo

				
			

For macOS :

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

				
			

For Fedora/RHEL/CentOS :

				
					sudo dnf install epel-release
sudo dnf install jpegoptim optipng pngquant gifsicle libwebp-tools libavif-tools
sudo npm install -g svgo

				
			

These tools will handle various image formats like JPEG, PNG, GIF, SVG, WebP, and AVIF.

Step 3 : Define Routes

Now, let’s create the necessary routes for our image upload functionality. Open the routes/web.php file and add the following routes :

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

Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');

				
			

Step 4 : Create the Image Controller

Next, we’ll create an ImageController to handle the image upload and compression. Run the following Artisan command to generate the controller :

				
					php artisan make:controller ImageController

				
			

Open the newly created ImageController.php in app/Http/Controllers and update it with the following code:

				
					namespace App\Http\Controllers;

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

class ImageController extends Controller
{
    public function index(): View
    {
        return view('imageUpload');
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

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

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

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

				
			

Step 5 : Create the Upload View and Directory

Next, we’ll create the imageUpload.blade.php file that will contain our HTML form for uploading images. In your resources/views directory, create a file named imageUpload.blade.php and add the following code :

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 Compress Image Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
<div class="container mt-5">
    <div class="card">
        <div class="card-header">
            <h3><i class="fa fa-image"></i> Laravel 11 Image Compression Example</h3>
        </div>
        <div class="card-body">
            @if ($errors->any())
                <div class="alert alert-danger">
                    <strong>Whoops!</strong> There were some problems with your input.<br><br>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    <strong>{{ $message }}</strong>
                </div>
                <img decoding="async" src="images/{{ Session::get('image') }}" class="img-fluid mt-3">
            @endif

            <form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="mb-3">
                    <label for="inputImage" class="form-label">Select Image:</label>
                    <input type="file" name="image" id="inputImage" class="form-control @error('image') is-invalid @enderror">
                    @error('image')
                        <div class="invalid-feedback">{{ $message }}</div>
                    @enderror
                </div>
                <button type="submit" class="btn btn-primary"><i class="fa fa-upload"></i> Upload & Compress</button>
            </form>
        </div>
    </div>
</div>
</body>
</html>

				
			

Finally, ensure that you’ve created the images directory inside the public directory where the optimized images will be stored.

Step 6 : Run the Application

With everything set up, it’s time to test your application. Run the Laravel development server with the following command:

				
					php artisan serve

				
			

Now, navigate to http://localhost:8000/image-upload in your web browser. You should see the image upload form. Select an image, upload it, and see the optimized version of the image displayed on the page.

Conclusion :

By following this guide, you’ve successfully integrated the Spatie/Image package into your Laravel 11 application for compressing and optimizing images. This setup not only reduces image file sizes but also enhances your application’s performance. Implementing such optimizations is vital for delivering a better user experience, especially on image-heavy websites.

Feel free to expand on this example by adding more features, such as automatic resizing, custom compression levels, or integration with cloud storage.

Scroll to Top