Tech Verse Logo
Enable dark mode
Optimize Images in Laravel with Intervention Image

Optimize Images in Laravel with Intervention Image

•Updated •9 min read

Install intervention/image-laravel, decode uploads with Image::decode(), shrink them with scaleDown(1600, 1600) and encode with encodeUsingFormat(Format::WEBP, quality: 75). Turn on strip in config/intervention-image.php so GPS data never reaches the public, prefer Imagick over GD for large photos, and build responsive widths in a queued job for srcset.

A phone photo is a 12-megapixel JPEG of two to five megabytes, and if your upload form stores it as-is, every page that shows it ships all of that to the browser. Compressing images in Laravel comes down to three steps: shrink the pixels to the largest size you'll actually display, re-encode to WebP (or AVIF) at a sensible quality, and strip the metadata. intervention/image-laravel does all three, but the package has moved to a new major release with a different API, so a lot of the code you'll find online, with Image::read() and toWebp(), no longer runs.

Installing Intervention Image in Laravel

Install the Laravel integration; it pulls in intervention/image itself. The current release needs PHP 8.3 or newer and either the GD or Imagick extension.

composer require intervention/image-laravel
php artisan vendor:publish --provider="Intervention\Image\Laravel\ServiceProvider"

Publishing creates config/intervention-image.php (older guides say config/image.php, which was the previous name). This is the published file with the comments removed and one change: strip is switched on, for reasons covered below.

<?php

return [
    'driver' => env('IMAGE_DRIVER', \Intervention\Image\Drivers\Gd\Driver::class),

    'options' => [
        'autoOrientation' => true,
        'decodeAnimation' => true,
        'backgroundColor' => 'ffffff',
        'strip' => true,
    ],
];

If you used an earlier version, these are the renames you'll hit first. Image::read() is now Image::decode(), with specific variants such as decodePath() and decodeBinary(). The toJpeg(), toWebp() and toAvif() family is replaced by encodeUsingFormat() with a Format enum, or encode() with an encoder object. pad() became containDown(). The full list is in the Intervention Image upgrade guide.

GD or Imagick?

Use Imagick if you can install it, and GD if you can't. The official docs recommend Imagick for larger images, and two things from my test run back that up. The first is memory. GD decodes the whole bitmap into PHP's own memory, so it counts against memory_limit: decoding and scaling the 12-megapixel test photo peaked at 71 MB of PHP memory, a 20-megapixel photo at 102 MB, and a 12-megapixel photo that needed EXIF auto-rotation blew straight through the default 128 MB limit with "Allowed memory size of 134217728 bytes exhausted". ImageMagick allocates its own memory outside PHP, so memory_limit doesn't see it. That doesn't mean it uses less, only that the limit won't stop it.

The second is formats. AVIF output depends on how the PHP extension was built, not on Intervention. On my machine GD had no AVIF support, and calling encodeUsingFormat(Format::AVIF) on the GD driver died with "Call to undefined function Intervention\Image\Drivers\Gd\Encoders\imageavif()". Check before you plan around it:

php -m | grep -iE '^(gd|imagick)$'
php -r 'var_dump(function_exists("imageavif"));'
php -r 'print_r(Imagick::queryFormats("AVIF"));'

Switch drivers in .env without touching code:

IMAGE_DRIVER=Intervention\Image\Drivers\Imagick\Driver

There's also a libvips driver, shipped separately as intervention/image-driver-vips. It needs the libvips library and PHP's FFI extension, and I didn't test it here.

Resizing and scaling uploads

Use scaleDown() for uploads. scale() keeps the aspect ratio and works out the missing dimension for you (that's Intervention doing it, not Laravel). scaleDown() does the same but never enlarges a smaller image, and if you pass both a width and a height it fits the image inside that box. scaleDown(1600, 1600) turned the 4032×3024 landscape photo into 1600×1200, and turns a portrait photo into 1200×1600, with no if/else on orientation. Plain resize() forces exact dimensions and distorts the picture, which is rarely what you want.

Here's a complete upload endpoint that resizes, converts to WebP and stores the result on the public disk:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Format;
use Intervention\Image\Laravel\Facades\Image;

class ImageUploadController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'image' => [
                'required',
                'image',
                'mimes:jpg,jpeg,png,webp',
                'max:10240',
                'dimensions:max_width=8000,max_height=8000',
            ],
        ]);

        $encoded = Image::decode($request->file('image'))
            ->scaleDown(1600, 1600)
            ->encodeUsingFormat(Format::WEBP, quality: 75);

        $path = 'images/'.Str::uuid().'.webp';

        Storage::disk('public')->put($path, (string) $encoded);

        return response()->json(['url' => Storage::disk('public')->url($path)], 201);
    }
}

The dimensions rule matters more than the max file size. A PNG of a few kilobytes can declare a 20,000-pixel canvas, and it's the pixel count that decides how much memory decoding takes. The rule rejected a 9000-pixel-wide test image with a 422 before Intervention touched it; the Laravel validation docs on the dimensions rule list its other options.

For thumbnails, the choice is between cover(), which fills the box exactly and crops whatever overflows from the centre, and containDown(), which keeps the whole picture and pads the rest with a background colour. containDown() is the old pad(): a 700×500 image came out as an 800×800 tile with the photo at its original size in the middle, not stretched.

<?php

namespace App\Images;

use Intervention\Image\Format;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Laravel\Facades\Image;

class Thumbnails
{
    // Fill a 256x256 square, cropping the overflow from the centre.
    public function avatar(string $binary): EncodedImageInterface
    {
        return Image::decodeBinary($binary)
            ->cover(256, 256)
            ->encodeUsingFormat(Format::WEBP, quality: 75);
    }

    // Keep the whole picture and pad it to an 800x800 white square.
    public function productTile(string $binary): EncodedImageInterface
    {
        return Image::decodeBinary($binary)
            ->containDown(800, 800, 'ffffff')
            ->encodeUsingFormat(Format::WEBP, quality: 80);
    }
}

Both produced the sizes you'd expect from the 4032×3024 photo: a 256×256 avatar at about 12 KB and an 800×800 tile at about 63 KB. The Intervention resizing reference covers the rest of the family, including coverDown() and resizeCanvas().

Encoding to WebP and AVIF with a quality setting

Encoding is where the bytes go away. encodeUsingFormat() takes a Format case plus encoder options such as quality (0 to 100) and strip, and returns an encoded image you can cast to a string, save() to a local path, or hand to Storage. The Intervention image output docs also show encodeUsingMediaType(), encodeUsingFileExtension() and encoder objects such as new WebpEncoder(quality: 65).

For a sense of scale, here's what my run produced from the 2.5 MB iPhone photo scaled to 1600×1200 with the Imagick driver. JPEG came out at 183 KB, 237 KB and 407 KB at quality 60, 75 and 90. WebP was 125 KB, 147 KB and 294 KB at the same settings. AVIF was 144 KB, 220 KB and 410 KB: larger than WebP at every quality number. That's not a verdict on AVIF. The quality number means something different to each encoder, so "70" in AVIF isn't "70" in WebP, and the fair comparison is file size at the same visual quality, which only your eyes or a metric tool can judge. What it does mean is that you shouldn't ship AVIF at the same number as WebP and assume you've saved bandwidth. Compare on your own images.

I'd default to WebP at 70 to 75. Every current browser decodes it, and the drop from a 2.5 MB original to roughly 130 KB is where nearly all the saving is. Add AVIF only after you've checked that it wins on your images.

Stripping metadata

Turn strip on, for privacy as much as size. The test photo carried its camera model and GPS coordinates. With the Imagick driver and the default config (strip false), the resized WebP and JPEG kept all of it, GPS included, so anyone downloading the image from your site could read where it was taken. With strip set to true in the config, or passed per call as encodeUsingFormat(Format::WEBP, quality: 75, strip: true), the GPS tags were gone and the 1600-pixel WebP shrank from 147 KB to 132 KB. The Imagick strip keeps the ICC colour profile, so colours don't shift.

GD never wrote EXIF to its output in my tests, with or without strip. Don't rely on that if you might switch drivers later; set the option explicitly.

One related setting: autoOrientation (on by default) rotates the pixels according to the EXIF orientation tag while decoding. A photo tagged as rotated 90 degrees decoded as 3024×4032 with it on and 4032×3024 with it off, so leave it on, or portrait phone photos will come out sideways once their metadata is stripped.

Doing the work in a queued job and storing to a disk

Generating several sizes in two formats takes long enough that it doesn't belong in the request. Store the original on a private disk, return straight away, and let a queued job do the rest. This assumes a Photo model with original_path, width, height and a variants JSON column cast to an array.

<?php

namespace App\Http\Controllers;

use App\Jobs\GenerateImageVariants;
use App\Models\Photo;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PhotoController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'image' => ['required', 'image', 'max:10240', 'dimensions:max_width=8000,max_height=8000'],
        ]);

        $photo = Photo::create([
            'original_path' => $request->file('image')->store('originals', 'local'),
        ]);

        GenerateImageVariants::dispatch($photo);

        return response()->json(['id' => $photo->id], 202);
    }
}

The job decodes once, works out which formats the active driver can write, and produces each width from largest to smallest by shrinking the same image again. That keeps a single full-size bitmap in memory. Cloning the source for each width was the first version I tried, and on GD it ran out of memory at 128 MB; the shrinking version peaked at 106 MB and finished.

<?php

namespace App\Jobs;

use App\Models\Photo;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Format;
use Intervention\Image\Laravel\Facades\Image;

class GenerateImageVariants implements ShouldQueue
{
    use Queueable;

    public const WIDTHS = [480, 960, 1600];

    public int $timeout = 120;

    public function __construct(public Photo $photo) {}

    public function handle(): void
    {
        $image = Image::decodeBinary(Storage::disk('local')->get($this->photo->original_path));

        $this->photo->fill(['width' => $image->width(), 'height' => $image->height()]);

        $formats = array_filter(
            [Format::AVIF, Format::WEBP],
            fn (Format $format) => $image->driver()->supports($format),
        );

        // Largest first, shrinking the same image each pass, so only one
        // full-size bitmap is ever in memory. Never upscale.
        $widths = collect(self::WIDTHS)
            ->map(fn (int $width) => min($width, $image->width()))
            ->unique()
            ->sortDesc();

        $variants = [];

        foreach ($widths as $width) {
            $image->scale(width: $width);

            foreach ($formats as $format) {
                $extension = strtolower($format->name);
                $path = "photos/{$this->photo->id}/{$width}.{$extension}";

                Storage::disk('public')->put($path, (string) $image->encodeUsingFormat($format, quality: 70));

                $variants[$extension][$width] = $path;
            }
        }

        $this->photo->variants = array_map(fn (array $set) => array_reverse($set, true), $variants);
        $this->photo->save();
    }
}

Reading through Storage::disk('local')->get() and writing through Storage::disk('public')->put() means the same job works unchanged when either disk points at S3; the Laravel filesystem docs cover the disk configuration. With the Imagick driver, the job wrote six files for the iPhone photo. The WebP variants were 23 KB, 60 KB and 123 KB at 480, 960 and 1600 pixels wide. The AVIF ones were 28 KB, 79 KB and 176 KB. Under GD, AVIF was skipped automatically and only the WebP set was written. A 700-pixel upload got 480 and 700, never an upscaled 960.

Make sure the worker has the same image extension and the same memory_limit headroom as you tested with. It's common for the CLI php.ini on a server to differ from the FPM one.

Serving responsive sizes

Generating sizes only helps if the browser can pick between them, which is what srcset and sizes are for. This Blade component renders a <picture> element with an AVIF source when there is one and WebP otherwise:

@props(['photo', 'alt', 'sizes' => '(min-width: 1024px) 960px, 100vw'])

@php
    $srcset = fn (string $format) => collect($photo->variants[$format] ?? [])
        ->map(fn (string $path, int $width) => Storage::disk('public')->url($path)." {$width}w")
        ->implode(', ');

    $largest = collect($photo->variants['webp'] ?? [])->last();
@endphp

@if ($largest)
    <picture>
        @if (! empty($photo->variants['avif']))
            <source type="image/avif" srcset="{{ $srcset('avif') }}" sizes="{{ $sizes }}">
        @endif
        <img
            src="{{ Storage::disk('public')->url($largest) }}"
            srcset="{{ $srcset('webp') }}"
            sizes="{{ $sizes }}"
            width="{{ $photo->width }}"
            height="{{ $photo->height }}"
            alt="{{ $alt }}"
            loading="lazy"
            decoding="async"
        >
    </picture>
@endif

Use it as <x-photo :photo="$photo" alt="Peanut ice cream roll" />. It renders nothing until the job has filled in variants, so show a placeholder in that window if you need one. The width and height attributes are the original dimensions. They only give the browser the aspect ratio so it can reserve space and avoid layout shift, so pair them with max-width: 100%; height: auto in your CSS. Getting sizes right is the part people skip: it tells the browser how wide the image will be displayed before CSS loads, and if you leave it out the browser assumes 100vw and downloads the largest file on desktop. If your front end is Next.js rather than Blade, the same reasoning applies to its image component's sizes prop. MDN's guide to responsive images explains how the browser picks a candidate.

If you'd rather not keep AVIF, drop Format::AVIF from the job and the component falls back to a plain <img> with a WebP srcset, which is a perfectly good place to stop.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData