Search by

id-sign / image-bundle

NovakHonza

Symfony bundle for automatic image optimization — resize, format negotiation (AVIF/WebP), srcset, blur placeholder, HTTP cache headers.

Package info

github.com/id-sign/image-bundle

Type:symfony-bundle

pkg:composer/id-sign/image-bundle

Statistics

Installs: 550

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

0.6.2 2026-12-06 08:49 UTC

README

Lightweight yet powerful image optimization bundle for Symfony. Provides a <twig:Image> component that generates <picture> tags with automatic resize, client-side format negotiation (AVIF/WebP), responsive srcset, blur placeholders, watermark profiles, and HMAC-signed URLs.

Built on ext-imagick with no additional dependencies — zero CLI tools, no third-party image libraries. Designed for performance: web server serves cached images directly via try_files with no PHP overhead. Extensible through interfaces for custom image sources and cache storage. Ready for FrankenPHP worker mode.

Requirements

  • PHP 8.2+
  • Symfony ^7.4 | ^8.0 with FrameworkBundle (its router resolves route_prefix in the bundle route, and it provides kernel.secret, from which the URL signing key is derived)
  • ext-imagick, with ImageMagick built with the lcms delegate (magick -list configure | grep DELEGATES, convert on ImageMagick 6) — it performs the ICC colour conversion; without it profiled sources are logged and served unconverted, see Colour profiles and metadata

Installation

composer require id-sign/image-bundle

If Symfony Flex doesn't register the bundle automatically, add it to config/bundles.php:

// config/bundles.php
return [
    // ...
    IdSign\ImageBundle\IdSignImageBundle::class => ['all' => true],
];

Import the bundle routes:

# config/routes/id_sign_image.yaml
id_sign_image:
    resource: '@IdSignImageBundle/config/routes.yaml'

Configuration

# config/packages/id_sign_image.yaml
id_sign_image:
    # Breakpoints for responsive srcset generation
    # A later config file (e.g. a when@prod block) replaces the list instead of extending it.
    device_sizes: [ 320, 480, 640, 750, 828, 1080, 1200, 1920, 2048, 3840 ]

    # Default output quality (1-100)
    default_quality: 80

    # Output quality per format (1-100) for the formats listed; the others use default_quality.
    # Keys: avif, webp, jpeg, png ("jpeg", never "jpg"). Default: none.
    format_quality:
        avif: 55
        webp: 75

    # Named image sources (name => absolute base path), referenced as "@name/path" in src.
    # Paths without a prefix use "default"; when omitted, default is %kernel.project_dir%/data.
    sources:
        default: '%kernel.project_dir%/data'
        reference: '%kernel.project_dir%/assets/reference'

    # Output formats in priority order (used for <source> elements in <picture>): avif, webp, jpeg, png.
    # A later config file (e.g. a when@prod block) replaces the list instead of extending it.
    formats: [ 'avif', 'webp' ]

    # Cache settings
    cache:
        ttl: 2592000            # 30 days in seconds (controller mode only); 0 = re-encode on every request (debugging)
        path: ~                 # absolute; default: %kernel.project_dir%/public + route_prefix, where try_files finds
                                # the files; controller mode with access control: move outside public/

    # Blur placeholder
    blur:
        enabled: false          # Global default; per image `blur` / `:blur="false"`
        size: 10                # Longer side of the placeholder sample in pixels, 1-64 (inlined into every page)
        quality: 90             # JPEG quality of the placeholder; below 90 the codec blocks show as blotches
        transparent: false      # true: placeholders for transparent sources too — needs your own script, see `blur`

    # Default watermark profile applied to all images (null = no watermark); must be one of the profiles below
    default_watermark: ~

    # Named watermark profiles. Names may contain letters, digits, "_" and "-" and are kept verbatim — they are
    # what the watermark attribute and default_watermark refer to, and they appear in image URLs.
    watermarks:
        copyright:
            path: '%kernel.project_dir%/data/watermark.png'  # Absolute path to watermark image (PNG with transparency)
            position: 'bottom-right'  # top-left, top-center, top-right, center-left, center, center-right, bottom-left, bottom-center, bottom-right
            opacity: 50               # 0-100
            size: 20                  # Watermark width as percentage of output image width, 1-100 (see below)
            margin: 10                # Margin from edge in pixels of the output variant, ≥ 0 (see below)
        # Define additional profiles as needed:
        # client_logo:
        #     path: '%kernel.project_dir%/data/client-logo.png'
        #     position: 'top-right'
        #     opacity: 30
        #     size: 15
        #     margin: 20

    # Auto-calculate height from source aspect ratio when only width is provided
    auto_dimensions: false

    # Use lossless encoding by default (WebP/AVIF only — ignored for JPEG/PNG)
    lossless: false

    # Safety limits — protect against memory exhaustion and decompression bombs
    max_width: 4096                 # Reject a width or an explicit height above this (pixels)
    max_source_bytes: 20971520      # Reject source files above this (bytes). 0 disables.
    max_source_pixels: 64000000     # Reject source images above this many pixels (width × height). 0 disables.

    # Permissions for created cache files and directories
    file_permissions: 0o660       # octal with "0o" — YAML reads 0660 as a string; null = use umask default
    directory_permissions: 0o770  # the owner needs rwx

    # 'public' = web server serves cached files directly (try_files)
    # 'controller' = every request goes through PHP (TTL-based invalidation, access control); private, no-cache
    serve_mode: 'public'

    # URL prefix of every image URL: starts with "/", no trailing "/". The route and the default cache.path follow it —
    # import the bundle routes without a "prefix:".
    route_prefix: '/_image'

Usage

Basic

<twig:Image src="uploads/photo.jpg" width="800" height="600" alt="A photo" />

Output:

<picture>
    <source type="image/avif"
            srcset="/_image/.../320_auto_none_80.avif 320w, /_image/.../480_auto_none_80.avif 480w, /_image/.../640_auto_none_80.avif 640w, /_image/.../750_auto_none_80.avif 750w, /_image/.../800_auto_none_80.avif 800w"
            sizes="100vw">
    <source type="image/webp"
            srcset="/_image/.../320_auto_none_80.webp 320w, /_image/.../480_auto_none_80.webp 480w, /_image/.../640_auto_none_80.webp 640w, /_image/.../750_auto_none_80.webp 750w, /_image/.../800_auto_none_80.webp 800w"
            sizes="100vw">
    <img src="/_image/.../800_auto_none_80.jpeg" width="800" height="600" sizes="100vw" alt="A photo" decoding="async"/>
</picture>

height without fit is a layout hint: it lands on <img> for CLS prevention while the server resizes by width only (auto in the URL) and keeps the source aspect ratio — see height. One srcset candidate per default device_sizes breakpoint below width, plus width itself — see Picking sizes.

With blur placeholder and fit mode

<twig:Image
    src="uploads/hero.jpg"
    width="1200"
    height="600"
    fit="cover"
    blur
    alt="Hero image"
    class="w-full rounded-lg"
    loading="lazy"
    sizes="100vw"
/>

With watermark

{# Apply a specific watermark profile #}
<twig:Image src="uploads/photo.jpg" width="800" height="600" watermark="copyright" alt="Photo" />

{# Apply a different profile #}
<twig:Image src="uploads/photo.jpg" width="800" height="600" watermark="client_logo" alt="Photo" />

{# Disable watermark even if default_watermark is set globally #}
<twig:Image src="uploads/photo.jpg" width="800" height="600" :watermark="false" alt="Photo" />

{# Uses default_watermark from config (null = no watermark by default) #}
<twig:Image src="uploads/photo.jpg" width="800" height="600" alt="Photo" />

Custom quality

{# One quality for every format #}
<twig:Image src="uploads/avatar.jpg" width="64" height="64" quality="90" alt="Avatar" class="rounded-full" />

{# Per format — formats not named keep format_quality / default_quality #}
<twig:Image src="uploads/hero.jpg" width="1920" :quality="{avif: 70, webp: 90}" alt="Hero" />

SVG passthrough

SVG files are served without any image processing — no resize, no format conversion, no srcset. The file is copied to cache on first request and served via try_files (public mode) or controller. No HMAC signature is needed.

<twig:Image src="icons/logo.svg" width="120" height="40" alt="Logo" />

Output:

<img src="/_image/icons/logo.svg" width="120" height="40" alt="Logo" decoding="async"/>

Colour profiles and metadata

Every variant is written in sRGB without metadata. A source with an embedded ICC profile — Display P3 (every iPhone photo), Adobe RGB, a monitor profile in a screenshot, a CMYK press profile — is converted to sRGB through that profile before it is stripped, so the colours stay as intended; a source without a profile is taken as sRGB — except a camera JPEG shot in Adobe RGB mode, which carries no profile but says so in EXIF (InteroperabilityIndex R03) and is converted as Adobe RGB. A watermark image with a profile is converted the same way before it is composited. EXIF orientation is applied before the EXIF block is dropped. The conversion runs on the resized output (about 40 ms for 800 × 600) and only when a variant is generated; a source tagged with one of the sRGB profile variants (camera and Photoshop JPEGs) is recognised in about 2 ms and not converted. A profile that cannot be converted (truncated, or not matching the image) is logged as a warning and stripped without conversion. The sRGB target is the ICC's sRGB2014.icc, bundled in resources/; the bundle refuses to build the container when that file is missing. The conversion runs in LittleCMS through ImageMagick, on the profile embedded in the source file — keep lcms2 as current as ImageMagick itself. An ImageMagick built without the lcms delegate cannot convert at all: every profiled source is then logged as a warning on cache miss and served with the profile stripped, i.e. with the washed-out colours of 0.3.

Not handled, and taken as sRGB like browsers do: PNG files that declare their primaries only through cHRM/gAMA chunks, and AVIF/HEIC files whose colour space is given only by an nclx box without an ICC profile (avifenc, Pixelmator, Affinity; iPhone HEIC embeds a profile and is converted).

Animated images

An animated GIF, APNG or animated WebP is processed from its first frame: every variant and the placeholder are still images, the animation is lost. (The source limits still count every frame, see Decompression bombs.) Serve an animation as a plain file outside the component.

Component attributes

Attribute Type Required Description
src string yes Source path, optionally @source/-prefixed (see Image sources)
width int yes Intrinsic image width in px (not display size) — required, see below
height int no Display height, 1…max_width (auto-calculated if auto_dimensions enabled)
fit string no Resize mode: cover, contain, or scale-down
blur bool no Blur placeholder; :blur="false" switches off blur.enabled for this image
quality int|map no Output quality 1-100, or a {format: quality} map (see quality)
autoDimensions bool no Auto-calculate height from aspect ratio (overrides global auto_dimensions)
watermark string|false no Watermark profile name, false to disable, omit for global default
lossless bool no Use lossless encoding (WebP/AVIF only, overrides global config)

All other attributes (alt, class, id, loading, data-*, aria-*, etc.) are passed through to the <img> tag. sizes is the exception: it goes on every <source> and on <img> (see Picking sizes).

The bundle sets no loading itself. The main image of the page (the LCP element, typically a hero) gets fetchpriority="high" and never loading="lazy" — a lazy image waits for layout before it is requested. Images below the first screen get loading="lazy".

<twig:Image src="uploads/hero.jpg" width="1920" height="800" fit="cover" sizes="100vw" fetchpriority="high" alt="…" />
<twig:Image src="uploads/detail.jpg" width="800" autoDimensions loading="lazy" sizes="(min-width: 1024px) 33vw, 100vw" alt="…" />

Props are HTML attributes with the usual ux-twig-component rules: a plain attr="…" passes a string (width="800" is coerced to int), :attr="…" evaluates a Twig expression — needed for false, variables and anything that is not a literal string (:width="image.width", :watermark="false") — and a bare attribute means true (blur, lossless). The same props can be passed as a named map through the function syntax, handy in loops and macros where they come from variables:

{{ component('Image', { src: image.path, width: 800, fit: 'cover', alt: image.title, class: 'card__img' }) }}

src

Path to the source image relative to the default source directory (data/ unless configured). Prefix it with @name/ to read from another configured source, e.g. @reference/logo.png — see Image sources. @default/photo.jpg means the same as photo.jpg, and so does /photo.jpg — a leading slash is dropped, so every spelling shares one URL and one cache directory. The file must exist on the filesystem. For SVG files, no processing is applied — the image is served directly.

width

The intrinsic width of the generated image file in pixels — not the rendered CSS size. Used as the width HTML attribute (CLS prevention), as the main size in srcset, and as the upper bound for responsive breakpoints (SrcsetGenerator only emits device_sizes breakpoints ≤ width).

width is required and must be > 0 — omitting it (or passing 0) throws InvalidArgumentException at render time, applies to SVG as well. Pick a value that matches the largest pixel size the image will ever render at.

Picking the right value:

  • Full-bleed image (class="w-full", sizes="100vw"): use the largest realistic render size, typically the largest relevant device_sizes entry (e.g. 1920 or 2048). The browser picks from all breakpoints ≤ width.
  • Fixed-size image in a column: set width to the max CSS width the image can reach, optionally 2× for retina. Pair with a matching sizes, e.g. sizes="(min-width: 1024px) 500px, 100vw".
  • width smaller than smallest device_sizes entry (default 320) produces a single-candidate srcset — on wide viewports the image gets stretched and looks blurry. Raise width, or narrow sizes to reflect the real layout.
  • SVG: width only affects the <img width="…"> HTML attribute — no server-side processing happens. Pick the layout size you want reserved for CLS.

Mismatch between width and sizes wastes bandwidth or causes blurry rendering — see Picking sizes below.

Picking sizes

The sizes attribute tells the browser how wide the image will render at each viewport size. The browser multiplies that against DPR and picks the smallest srcset candidate ≥ the target. Without a correct sizes, responsive srcset is wasted bandwidth: sizes="100vw" makes every browser download the candidate for the full viewport width regardless of actual render size.

Give every image that does not span the full viewport a sizes matching the real CSS layout — lazy images too. The auto default below is a safety net for a forgotten sizes, not a replacement for it:

  • Browsers without sizes="auto" (before Chrome 126, Firefox 150, Safari 27) download the candidate for the full viewport width.
  • auto never applies to images loaded right away — the main image of the page (LCP) and everything in the first screen — nor to images whose aspect ratio the bundle does not know.
  • The main image of the page: an explicit sizes, fetchpriority="high", never loading="lazy" (it would wait for layout and the lazy-loading margin).

Common patterns:

  • Full-bleed (edge-to-edge): sizes="100vw" (the default outside the auto case below — only correct if the image truly spans the viewport).
  • Fixed max-width container with full-bleed mobile: sizes="(min-width: 1280px) 1280px, 100vw".
  • Grid column, breakpoint-dependent: sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw".
  • Fixed pixel size: sizes="400px".

Default: without sizes, the bundle writes sizes="auto, 100vw" when the image is loading="lazy" and the bundle knows the real aspect ratio of the file — fit="cover" with a height, a height computed from the source (autoDimensions, also with contain/scale-down), or scale-down with a source that fits the box — and srcset offers more than one candidate (not below the smallest device_sizes entry, not with formats: []). The browser then picks the candidate by the width the image is laid out at (a 400 px column on a 1280 px screen gets 480w, not 1280w). Otherwise — and in browsers without sizes="auto" — it is 100vw. auto needs exactly those conditions: browsers apply it only to lazy images, and their stylesheet gives every <img> whose sizes starts with auto — lazy or not — contain: size with its aspect ratio taken from width/height alone, so a height that does not match the file (a hint without fit, contain with a given height) would squash or distort the image. The same holds for a sizes="auto, …" you write yourself — prefer leaving auto to the bundle, which adds it only where it is safe; if you write it, then only with loading="lazy" and a height of the file's real ratio, and keep a real fallback after the comma (auto, (min-width: 1024px) 33vw, 100vw) for browsers without sizes="auto". Without auto, a height whose ratio differs from the file's shifts the layout (CLS) once the image loads; with auto the image is distorted instead. (fit="cover" crops the file to the box, so its height always matches.)

The width comes from the width attribute in the same way: CSS that overrides it on images with width: auto (some CMS themes and older resets) leaves auto images at the 300×150 of contain-intrinsic-size. The usual max-width: 100%; height: auto (Bootstrap, Tailwind) and a CSS width such as width: 100% are fine. With width: auto in your stylesheet, give sizes or switch the default off (below).

sizes goes on every <source> and on <img> with the same value (auto on a <source> applies only when <img> has it too). SVG gets none.

To keep 100vw everywhere — e.g. should a browser bug in sizes="auto" show up — decorate the resolver; it changes the component and image_attributes() alike:

#[AsDecorator(ImageAttributesResolverInterface::class)]
final class NoAutoSizes implements ImageAttributesResolverInterface
{
    public function __construct(#[AutowireDecorated] private readonly ImageAttributesResolverInterface $inner)
    {
    }

    public function resolve(string $src, int $width, ?int $height = null, ?string $fit = null, int|array|null $quality = null,
        string|false|null $watermark = null, ?bool $lossless = null, ?bool $autoDimensions = null, ?bool $blur = null,
        ?string $sizes = null, ?string $loading = null): ImageAttributes
    {
        $attributes = $this->inner->resolve($src, $width, $height, $fit, $quality, $watermark, $lossless, $autoDimensions, $blur, $sizes, $loading);

        return null === $sizes && 'auto, 100vw' === $attributes->sizes ? $attributes->withSizes('100vw') : $attributes;
    }
}

Pass sizes as any other attribute:

<twig:Image src="uploads/hero.jpg" width="1920" sizes="(min-width: 1280px) 1280px, 100vw" alt="Hero" class="w-full h-auto" />

height

The display height in pixels. When omitted and auto dimensions is enabled (globally via auto_dimensions config or per-component via autoDimensions prop), the height is automatically calculated from the source image's aspect ratio. When both width and height are provided with a fit mode, the server produces an image with exactly these dimensions. Without fit, height is only the HTML attribute: the server resizes by width and keeps the source aspect ratio — so give it the source's ratio (or use autoDimensions). A height of another ratio reserves the wrong box: the layout shifts once the image loads (CLS), and with sizes="auto" the image is distorted instead; the same holds for contain, and for scale-down over a larger source, with a given height. In development the profiler warns about it (Development warnings). A height below 1 or above max_width throws an InvalidArgumentException — the controller trusts the signature, and with fit="cover" a mistyped height="60000" would scale the source to cover that box before cropping.

autoDimensions

Overrides the global auto_dimensions config for this specific component instance. When true, height is auto-calculated from the source aspect ratio (if height is not provided). When false, auto-calculation is disabled even if the global config is enabled. When omitted (null), the global config value is used. When the source image does not exist, no height is rendered and the page still renders — the image itself returns 404. A source whose header cannot be read (a broken upload) renders the same way and is logged as a warning (see Logging); its image URL answers 500.

fit

Controls how the image is resized when both width and height are specified:

  • cover — fills the target dimensions, cropping any overflow. Crop is always centered. For custom crop positioning, omit fit and use CSS object-fit + object-position instead — this gives full control over the visible area in the browser.
  • contain — fits within the target dimensions, preserving aspect ratio (may leave empty space)
  • scale-down — same as contain, but never upscales images smaller than the target. When the source is smaller, the rendered width/height attributes, srcset and URL reflect the actual source size.

When omitted, the server resizes by width only and keeps the source aspect ratio; height then only sets the HTML attribute (see height). Any other value — fill, Cover, none — throws an InvalidArgumentException when the component is rendered, image_url() is called or ImageUrlGenerator builds the URL.

blur

Shows a blurred placeholder while the image loads. The blur is in the placeholder bitmap itself: the source is shrunk to blur.size px on its longer side (10 by default), enlarged 4× with a Gaussian filter and blurred on the server, and inlined as a JPEG data URI in the style of <img>:

<img src="…" width="1200" height="600"
     style="background-image:url(&quot;data:image/jpeg;base64,…&quot;);background-size:cover;background-position:center;background-repeat:no-repeat;background-clip:content-box;background-origin:content-box;"
     decoding="async" data-blur-placeholder="" alt="…">

No CSS filter, no onload, no JavaScript: the browser stretches the bitmap as a background and the opaque image covers it once loaded. The background stays under the image. A style you give is appended. <img> with a placeholder carries data-blur-placeholder (without one it does not) — a hook for your scripts and CSS, which should not rely on the inline style.

blur (a bare attribute) asks for a placeholder, :blur="false" switches off blur.enabled for one image; omitted, the configuration decides. Write false as an expression: blur="false" without the colon is the string "false", which counts as true.

  • No placeholder for a missing source (the image URL answers 404), one above the source limits, one that cannot be read (logged as a warning; a failure after the header — a damaged body, a resource limit — is cached as broken and tried again after 10 minutes, find such sources with grep -rlx broken --include='placeholder-*.txt' in the cache directory), an SVG — and by default a source with transparent pixels, see below.

  • First render: a placeholder is made on the first render that shows the image and cached from then on. Making one decodes the source — tens of ms for a JPEG photo, 0.3–1 s for a 12–24 MP PNG, WebP or HEIC — and a page makes all its missing placeholders in that one request. A listing of dozens of large non-JPEG sources can therefore run into max_execution_time on a cold cache (after the upgrade to 0.6, or a bulk import): open such pages once before the traffic does, or raise the limit for that time.

  • object-fit: contain (or scale-down) in a box of another aspect ratio leaves blurred bars next to the image: the background fills the box. Use the placeholder with fit="cover" or an image whose box has its aspect ratio.

  • CSP: the placeholder needs style-src 'unsafe-inline' (inline style) and img-src data:. Without them the browser drops the placeholder and the image renders sharp as usual — nothing breaks.

  • HTML size: every page carries the placeholder of every image that has one. Binary size before base64 (+⅓) for photos, by blur.size and blur.quality:

    blur.size quality: 90 quality: 100
    10 460–600 B 0.9–1.4 kB
    16 660–900 B 1.7–2.7 kB
    32 1.2–1.9 kB 4.7–7.6 kB
    64 2.3–4.6 kB 9–22 kB

    After gzip the default costs ~330 B of HTML per landscape photo. Below quality: 90 the JPEG blocks stretched ~25× show as blotches.

  • Generated on demand, cached in the source's cache directory as placeholder-{key}.txt; the key holds the settings, so changing blur.size, blur.quality or blur.transparent generates new placeholders without a purge.

Can be set globally via blur.enabled in bundle configuration. The component attribute overrides the global setting.

Transparent sources

A placeholder under an image with transparent pixels would show through for good, so by default such a source (one transparent pixel is enough; a fully opaque RGBA PNG still gets one) renders without a placeholder. Typical case: product photos on a transparent background. blur.transparent: true gives them a placeholder — then your application has to remove it once the image has loaded:

<script>
    // Register first, then handle the images already loaded — the other order misses an image that completes
    // in between. Capture phase on document also covers images inserted later (htmx, Alpine).
    const clearPlaceholder = (img) => img.decode().catch(() => {}).then(() => { img.style.backgroundImage = 'none'; });
    const isPlaceholderImage = (target) => target instanceof HTMLImageElement && target.hasAttribute('data-blur-placeholder');
    document.addEventListener('load', (e) => { if (isPlaceholderImage(e.target)) clearPlaceholder(e.target); }, true);
    document.addEventListener('error', (e) => { if (isPlaceholderImage(e.target)) e.target.style.backgroundImage = 'none'; }, true);
    document.querySelectorAll('img[data-blur-placeholder]').forEach((img) => { if (img.complete) clearPlaceholder(img); });
</script>
<noscript><style>[data-blur-placeholder]{background-image:none!important}</style></noscript>

Waiting for decode() keeps the image from flashing; removing the background from opaque images as well does no harm. The <noscript> rule hides placeholders when JavaScript is off; when the script fails to run, they stay — keep it in a file your CSP allows.

Custom placeholders

The placeholder comes from PlaceholderGeneratorInterface — point its service alias to your own implementation, or decorate it, and the component, image_attributes() and image_placeholder() use it:

use IdSign\ImageBundle\Service\Placeholder;
use IdSign\ImageBundle\Service\PlaceholderGeneratorInterface;

final class DominantColourPlaceholder implements PlaceholderGeneratorInterface
{
    public function generate(string $src): ?Placeholder
    {
        return Placeholder::fromBinary('image/png', $this->onePixelPng($src)); // null = no placeholder
    }

    public function getCacheKey(): string
    {
        return 'colour-1'; // change it whenever the output changes: new cache files, no purge
    }
}
# config/services.yaml
IdSign\ImageBundle\Service\PlaceholderGeneratorInterface:
    alias: App\Image\DominantColourPlaceholder
  • Return data and a type, Placeholder::fromBinary($mimeType, $data) — the bundle builds the data URI. Types: image/jpeg, image/png, image/webp, image/gif, image/avif, image/svg+xml; anything else throws. External URLs are not possible: a placeholder fetched from elsewhere would arrive as late as the image.
  • The bundle checks around your generator: the source exists and fits max_source_bytes / max_source_pixels before generate() runs; the result (a placeholder or null) is cached as placeholder-{getCacheKey()}.txt, read without TTL; one worker per source runs the generator (others render that page without the placeholder meanwhile). Throw UnreadableSourceException for a source that cannot be read; it and an ImagickException render the page without a placeholder, log a warning and mark the source broken for 10 minutes before the next attempt. Any other exception — a bug in your generator — reaches the page.
  • Your generator decides about transparent sources itself; blur.transparent applies to the default one.
  • The output goes into the HTML of every page with the image — keep it to a few hundred bytes (see the table above).

quality

Output compression quality (1-100). Lower values produce smaller files with more compression artifacts. Typical values: 60-80 for photos, 80-90 for detailed images.

The formats do not compress alike — AVIF reaches the look of a WebP or JPEG at a clearly lower value — so the quality can be set per format. Each <source> and the <img> fallback get the first of:

  1. the quality attribute — an int applies to every format, a map such as :quality="{avif: 70, webp: 90}" only to the formats it names;
  2. format_quality from the configuration;
  3. default_quality.

Map keys are output formats: avif, webp, jpeg, png (for PNG the value sets the zlib level and filter, not a visual quality). A value outside 1-100 or an unknown key throws an InvalidArgumentException; in the configuration it fails the container build. Tune the values by eye on your own images — the right AVIF value depends on the encoder build.

The quality is part of the URL and of the cache path, so changing format_quality or default_quality changes the URLs of the affected formats: the new variants are generated on first request, the old ones stay on disk until image:purge.

watermark

Selects a named watermark profile to apply. Profiles are defined in watermarks in the bundle configuration, each with its own image, position, opacity, size, and margin.

  • watermark="copyright" — applies the copyright profile
  • :watermark="false" — disables watermark even if default_watermark is set globally
  • Omitted — uses the default_watermark profile from config (null = no watermark)

Each watermark profile produces a separate cached file with a distinct URL, so the same image can exist with different watermarks or without one.

Size and margin. The watermark keeps its aspect ratio and is size % of the output width, but never larger than the output minus margin on each side — a square at size: 40 on a 1600×400 banner becomes 380×380, not 640×640. It is scaled up as well as down: make the watermark image at least as wide as it gets in the largest variant, a smaller one is enlarged and blurs — and no larger than that, it is decoded on every encode of a watermarked variant. margin is in pixels of the output variant and the same at every width, so in a small srcset candidate the watermark sits relatively further from the edge than in a large one; it is capped at a quarter of the side, so a small candidate of a wide crop still gets a visible watermark.

Replacing the watermark image changes no URL: finished variants keep the old watermark on disk, and in public mode browsers and CDNs keep them with immutable even after a purge. Put a new watermark under a new profile name. A watermark file that is missing or unreadable at runtime answers 500 for every watermarked variant not cached yet (the build does not check it, the file may be mounted only at runtime) — deploy it with the application.

A watermark protects the image only when the source is not reachable on its own (it does not lie in the public web directory) and no template, image_url() or ImageUrlGenerator call renders the same source with :watermark="false" or another profile — such a variant has its own validly signed URL. The signature only keeps a visitor from removing the watermark by editing the URL (without _wm-… it answers 403).

lossless

Switches the encoder into its lossless mode for formats that support it. Useful for screenshots, diagrams, UI assets, pixel art, and anything where quality=100 still visibly softens edges or introduces banding.

{# Single lossless asset #}
<twig:Image src="docs/screenshot.png" :width="1200" lossless />

{# With watermark #}
<twig:Image src="icons/diagram.png" :width="600" lossless watermark="copyright" />

{# Disable even if set globally #}
<twig:Image src="photos/hero.jpg" :width="1920" :lossless="false" />

Format matrix:

Output format lossless=true behaviour
webp True lossless WebP (separate codec path, not quality=100)
avif True lossless AVIF via libheif where the AV1 encoder plugin is present (see below); otherwise falls back to quality=100 ("visually lossless") rather than silently dropping to the lossy default
jpeg / jpg Silently ignored — JPEG has no lossless mode. quality applies normally
png Silently no-op — PNG is always lossless

Lossless encoding is 5-50× slower and produces 2-10× larger files than lossy at quality=80. For photographic content the visual difference is imperceptible; use lossless only where bit-exact pixels actually matter.

AVIF runtime requirement: libheif on Debian/Ubuntu 24.04+ ships without an AV1 encoder by default. Install libheif-plugin-aomenc on the host where PHP runs. Without it, AVIF lossless (and even lossy) encoding fails with no encode delegate for image format AVIF.

# Debian / Ubuntu 24.04+
apt-get install libheif-plugin-aomenc

lossless can be set globally via the lossless config key and overridden per-component via the prop. The global default is false.

Serve modes

Public mode (default)

Cached images are stored at a path matching the URL. The web server serves them directly via try_files, PHP is only called on the first request per variant.

PHP sends Cache-Control: public, max-age=31536000, immutable with the first response of a variant only. Every later request gets the file from the web server, with the web server's headers: without the configuration below only ETag and Last-Modified, so browsers guess how long the file stays fresh and keep asking again. A variant URL is meant to keep its content (a replaced source goes under a new name, see Writing and replacing source files), so the web server should send the same header.

Nginx (the fallback is the /index.php front controller of the standard Symfony vhost):

# http level
map $uri $image_svg_csp { ~*\.svg$ "sandbox"; default ""; }

# server level
location ^~ /_image/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header X-Content-Type-Options "nosniff" always;
    add_header Content-Security-Policy $image_svg_csp always;  # "sandbox" for .svg, empty = not sent otherwise
    try_files $uri /index.php$is_args$args;
}
  • ^~ stops nginx from checking regex locations, which otherwise take precedence over a prefix location. The usual block that sets long expires for image extensions would take the request: without the try_files fallback every variant that is not cached yet answers 404 and is never generated, with it the cached files get that block's expires instead of immutable. For the same reason a separate location ~* \.svg$ under /_image/ never applies — the SVG security headers (see Webserver hardening for SVG) belong in this block, the map limits the Content-Security-Policy to SVG.
  • The add_header lines apply to the static file only. The response of PHP after try_files — the first one of a variant included — comes from the PHP location with the bundle's headers, so nothing is sent twice.
  • add_header always adds the header: do not put expires into the same location, it would send a second Cache-Control.
  • An add_header in a location cancels every add_header of the server block for it: repeat the security headers you set there (HSTS and others) in this block.

Caddy: the standard Symfony Caddyfile (php_fastcgi plus file_server) serves the cached files — php_fastcgi tries the file first and file_server serves it. Add the caching header:

@image path /_image/*
header @image ?Cache-Control "public, max-age=31536000, immutable"

The ? sets the header only where the response has none. header applies to the responses of PHP as well, and without the ? a 403 or 404 of the bundle would carry immutable next to Symfony's no-cache.

A dedicated block needs its own file_server: php_fastcgi does not serve static files, and handle blocks exclude each other, so without it every cached image answers an empty 200.

handle /_image/* {
    try_files {path}
    php_fastcgi unix//run/php-fpm.sock
    file_server
}

FrankenPHP: php_server serves existing files from the web root before handing the request to PHP (its built-in try_files {path} {path}/index.php index.php), and @ in the URL (%40) works. Add the same two lines as for Caddy for the caching header.

Apache: the standard Symfony vhost (FallbackResource /index.php or the symfony/apache-pack rewrite rules) serves the cached files. Add the caching header with mod_headers (a2enmod headers on Debian/Ubuntu):

<Location "/_image/">
    Header always setifempty Cache-Control "public, max-age=31536000, immutable"
</Location>

With the standard vhost the request for a variant that is not cached yet is redirected internally to /index.php, and the <Location> no longer applies to the response of PHP. always setifempty keeps the bundle's own header also where PHP is reached without that redirect (e.g. ProxyPassMatch): without always, mod_headers does not see the headers of a proxied response and adds a second Cache-Control.

mod_expires (ExpiresByType image/…, e.g. from the h5bp rules) adds a Cache-Control: max-age of its own — to the cached files next to the one above, and to the responses of PHP as well, the controller-mode ones included. Switch it off for the image URLs; the condition on the original request line also covers PHP after the internal redirect, which a <Location> does not:

<If "%{THE_REQUEST} =~ m#^\S+ /_image/#">
    ExpiresActive Off
</If>

Controller mode

Every image request goes through PHP. Enables TTL-based cache invalidation -- expired variants are regenerated on the next request. Use this when you need access control or TTL-based refresh. Set serve_mode: controller whenever the cache is outside the document root — the bundle picks the caching headers by it (see below).

For access control, move cache.path out of the document root. With the default (%kernel.project_dir%/public plus route_prefix) a standard Symfony vhost (try_files $uri /index.php$is_args$args) serves an already cached variant as a static file: the first authorized visitor fills the cache, everybody after them gets the file without PHP, and the firewall never sees the request.

In both modes a cached variant is served without consulting the source, so deleting a source file does not remove its variants: call deleteBySource() or image:purge <src> --force when a source is deleted (see Cache management). In controller mode the variants then expire with cache.ttl at the latest.

Responses in controller mode are Cache-Control: private, no-cache with Last-Modified: the browser asks on every view, so the firewall decides every time — revoked access and a logout take effect at once — and an unchanged variant costs a 304 Not Modified without the file. A variant re-encoded after cache.ttl has a new Last-Modified and reaches the browser. No shared cache — a CDN, a reverse proxy — stores the responses (see Shared caches and CDN). Public mode sends public, max-age=31536000, immutable from PHP, for the first request of a variant; the web server sends the cached file after it, with the header from the public mode examples.

id_sign_image:
    serve_mode: 'controller'
    cache:
        ttl: 86400  # Re-generate after 24 hours
        path: '%kernel.project_dir%/var/image-cache'  # outside public/, see above

Custom route prefix

Set route_prefix — the route and the default cache directory follow it:

id_sign_image:
    route_prefix: '/media/images'

The bundle route takes its path from route_prefix ('%id_sign_image.route_prefix%/{path}'), so import @IdSignImageBundle/config/routes.yaml without a prefix: — a prefix on the import would be applied on top. The default cache.path follows too (%kernel.project_dir%/public/media/images), so in public mode the web server finds the cached files under the URL path. If you set cache.path yourself in public mode, it has to be the document root plus route_prefix. The web server snippets, access_control rules and nginx locations in this README use the default /_image — replace it with your prefix. A container parameter works (route_prefix: '%app.images_prefix%', shared with access_control or a web server template) and is validated by its value; an %env()% value does not, because the route path and the default cache directory are fixed when the container is built.

Pick a prefix whose directory belongs to the bundle alone. The cache directory — by default the document root plus route_prefix — is emptied by image:purge (see Cache management), files of your own in it included. route_prefix: /images over a public/images/ that holds your static images loses them on the first purge. A configuration in which the cache directory is a source directory or contains one (sources.default: '%kernel.project_dir%/public/images' with route_prefix: /images) fails the container build, and so does a watermark path inside the cache directory — the first purge would delete it and every watermarked variant would answer 500.

Restricting access to authenticated users

Use controller mode with Symfony security to require authentication for image access:

# config/packages/id_sign_image.yaml
id_sign_image:
    serve_mode: 'controller'
    cache:
        path: '%kernel.project_dir%/var/image-cache'  # must not be under public/
# config/packages/security.yaml
security:
    access_control:
        - { path: ^/_image, roles: ROLE_USER }   # your route_prefix

In public mode, the web server serves cached files directly and bypasses PHP — Symfony's security firewall is not involved. The same happens in controller mode while cache.path stays under the document root: the web server's try_files finds the cached variant and serves it without PHP. Controller mode with the cache outside public/ is what makes the firewall see every request.

Shared caches and CDN

A cache between the browser and the application must not keep a protected image either: it would hand it to anyone who has the URL, without asking the firewall. Controller mode therefore answers Cache-Control: private — whatever the firewall is, with a session or stateless (a token, HTTP Basic, an API key). Do not override it with a CDN rule that caches regardless of Cache-Control ("cache everything") for the image route.

An application that uses controller mode only for cache.ttl, with no access control in front of the route, can put the responses back into the CDN with a response listener:

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

#[AsEventListener]
final class PublicImageCacheListener
{
    public function __invoke(ResponseEvent $event): void
    {
        $response = $event->getResponse();
        // Only for an image route without access control — see above.
        if ('id_sign_image' !== $event->getRequest()->attributes->get('_route')
            || !($response->isSuccessful() || 304 === $response->getStatusCode())) {
            return;
        }

        $response->headers->removeCacheControlDirective('no-cache');
        $response->setPublic();
        $response->setMaxAge(86400); // how long the CDN serves a variant without asking; a re-encoded one after that
    }
}

Keep the image route out of anything that uses the session — a stateful firewall (give ^/_image a firewall with security: false), a listener that reads the locale from the session. Symfony's session listener turns a response to a request that used the session back into private, max-age=0, after this listener; the images then silently miss the CDN.

Handing cached files to the web server (X-Accel-Redirect / X-Sendfile)

In controller mode PHP streams every cached file through Symfony's BinaryFileResponse. With X-Accel-Redirect (nginx, FrankenPHP) or X-Sendfile (Apache mod_xsendfile) PHP answers with a header only and the web server sends the file itself: sendfile, range requests and slow clients stop being PHP's business, while the firewall and the controller still run for every request, so access control is unchanged. With nginx + PHP-FPM the worker is already released once nginx has buffered the response, so the gain there is the CPU and memory of copying the file through PHP and FastCGI; with FrankenPHP, where PHP writes straight to the client connection, it also frees the PHP thread from slow clients. The bundle needs no configuration for this — it is the standard BinaryFileResponse support.

  1. Keep cache.path outside the document root (required for access control in controller mode, see above) and let Symfony trust the X-Sendfile-Type request header:

    # config/packages/framework.yaml
    framework:
        trust_x_sendfile_type_header: true   # Symfony 7.2+: or SYMFONY_TRUST_X_SENDFILE_TYPE_HEADER=1
  2. Tell the web server to pass the type and the path mapping to PHP and to serve the cache directory from an internal location. nginx:

    location ~ ^/index\.php(/|$) {
        # ... fastcgi_pass etc.
        fastcgi_param HTTP_X_SENDFILE_TYPE X-Accel-Redirect;
        fastcgi_param HTTP_X_ACCEL_MAPPING /var/www/app/var/image-cache/=/_image_internal/;
    }
    
    location /_image_internal/ {
        internal;
        alias /var/www/app/var/image-cache/;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Content-Security-Policy $image_svg_csp always;  # "sandbox" for .svg, empty = not sent otherwise
    }

    with, at http level, map $uri $image_svg_csp { ~*\.svg$ "sandbox"; default ""; }. nginx keeps Content-Type and Cache-Control from the PHP response, so the caching headers survive, but it drops the rest — including the SVG security headers the controller sets (see Webserver hardening for SVG), hence the two add_header lines. FrankenPHP and Apache below keep every header of the PHP response and need nothing extra.

    FrankenPHP (after its X-Sendfile documentation, for a cache in var/image-cache of an application in /app, the working directory of the FrankenPHP image):

    root public/
    
    request_header X-Sendfile-Type x-accel-redirect
    request_header X-Accel-Mapping /app/var/image-cache/=/
    
    intercept {
        @accel header X-Accel-Redirect *
        handle_response @accel {
            root var/image-cache/
            rewrite * {resp.header.X-Accel-Redirect}
            method * GET
            header -X-Accel-Redirect
            file_server
        }
    }
    
    php_server

    The mapping has to be absolute: the relative ../var/image-cache of the FrankenPHP documentation never matches, because BinaryFileResponse compares it with the file's realpath() — PHP then streams the file itself, without an error. root is relative to FrankenPHP's working directory (or absolute).

    Apache with mod_xsendfile (libapache2-mod-xsendfile on Debian/Ubuntu) and mod_headers:

    XSendFile On
    XSendFilePath /var/www/app/var/image-cache
    RequestHeader set X-Sendfile-Type X-Sendfile

    In every mapping the path is the absolute, symlink-resolved cache.path — BinaryFileResponse matches it against realpath(), so with a deployment symlink (current -> releases/42) give the resolved release path. A mapping that does not match is silent: PHP streams the file. An offloaded response carries an ETag from the web server, which BinaryFileResponse never sends — a quick curl -I shows whether the hand-over works.

URL security

All raster image URLs are signed with HMAC-SHA256 derived from kernel.secret. The signature is part of the URL path, so any modification of parameters (width, height, quality, etc.) results in a 403 Forbidden response. This prevents cache exhaustion attacks where an attacker generates arbitrary image variants.

The output format is not part of the signature (one signature covers every <source> of a width), so the controller generates only the formats the application links to: the configured formats plus the source's fallback format. Any other extension answers 404. The fallback format follows the source extension and is also the format of the <img> fallback of <twig:Image>:

Source extension Fallback format
jpg, jpeg jpeg
png png
webp webp
avif avif
gif, tiff, tif, heic, heif, bmp, other jpeg

When the formats carry different qualities (format_quality or a quality map), each signed quality can still be requested in every offered format — the …_55.avif URL also yields …_55.webp and …_55.jpeg. A width then has at most one variant per offered format and distinct quality (9 instead of 3 with avif, webp and a JPEG fallback), which bounds what an attacker can generate from the URLs on your pages. This is an accepted trade-off that keeps a single, format-free signature scheme for every URL.

SVG URLs are not signed — SVG has no parameter variations, so HMAC would add no protection against cache exhaustion. See Security model below for the implications.

Security model

Report vulnerabilities privately through GitHub's private vulnerability reporting — see SECURITY.md.

The bundle's threat model treats every configured source directory (sources, default %kernel.project_dir%/data) as a publicly accessible asset tree. Any file under any of them can be fetched by anyone who knows or guesses the path:

  • Raster images — attacker needs a valid HMAC signature (generated by your application) to access any specific (src, width, height, …) combination. They cannot forge arbitrary sizes or qualities. But the source file itself is public as soon as you render it anywhere with <twig:Image> or image_url().
  • SVG files — no signature is required. Any .svg file under any source directory is readable by anyone who knows or guesses the path (/_image/@reference/anything.svg).
  • Watermarks — protect an image only under the conditions in watermark.

What this means for your project

Do not store access-controlled or non-public files under any source directory. Adding a directory to sources publishes it. The bundle does not enforce authorization. If you need:

  • Authorization per user/role: use serve_mode: controller with cache.path outside the document root and add an access_control rule for the bundle route (see Restricting access to authenticated users). In public mode — and in controller mode with the cache under public/ — the web server serves cached files directly and bypasses Symfony security.
  • Authorization per image: enforce it before the bundle route as well — a firewall rule, a request listener at default priority (it runs after the router and the firewall, so it sees the route, the path attribute and the user) or a controller of your own that checks the src and forwards. A custom ImageSourceInterface cannot do it: a cached variant is served without consulting the source (see Serve modes), so an exists() that returns false for some users only takes effect while the variant is not cached yet.
  • Private storage with controlled access: implement a custom ImageSourceInterface pointing at a non-public location, and use serve_mode: controller with access control in front of the route.

Path traversal and symlinks

Input paths (src values) are checked for .., ., empty and backslash-containing segments (Windows takes \ as a separator too) and rejected at the source and cache layer (404 from the controller). Symlinks are followed transparently — the bundle assumes any symlink inside the source directory was placed there intentionally by the administrator. If you don't want symlinks followed, audit your source tree (e.g. find data/ -type l) and remove unexpected ones before relying on the boundary.

Decompression bombs

max_source_bytes (default 20 MiB) rejects oversized source files, and max_source_pixels (default 64 million pixels, 64 MP) rejects images whose header announces more pixels than that. The byte limit alone is not enough: a highly compressed 100 MP JPEG is about 15 MB and a flat 30 000 × 30 000 PNG a few hundred kB, yet decoding either needs over a gigabyte — above ImageMagick's memory policy it falls back to a disk-backed pixel cache that takes seconds to minutes per variant. Both checks run before Imagick decodes anything (the pixel check reads only the header, every frame of a GIF, APNG, animated WebP or multi-page TIFF counted — only the first frame is processed) and the image URL answers 413; a page that renders such an image gets no height and no blur placeholder, like for a missing source. These limits are a safety net, not upload validation — see Validating uploaded images. Raise max_source_pixels for medium-format photography (100 MP and more) or set it to 0 to disable the check. Also configure ImageMagick's policy.xml to restrict memory/width/height limits and disable dangerous coders (MVG, MSL, PDF, EPHEMERAL, URL). The bundle cannot substitute for a properly configured ImageMagick policy.

SVG and XSS

SVG files can contain <script> and event handlers that execute in your origin when the SVG is loaded as a top-level document. The bundle serves SVGs as-is — it does not strip scripts — but the controller sends them with Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff, which block script execution. In public mode cache hits never reach the controller, so the web server has to add the same headers (see Webserver hardening for SVG below). If your source directory can receive user-uploaded SVGs, either sanitize before storage or make sure every served response carries those headers.

Webserver hardening for SVG

The controller sends SVG with Content-Type: image/svg+xml, Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff. In controller mode that is every response — unless the file is handed over with X-Accel-Redirect, which drops those headers, see above. In public mode PHP answers only the first request for an SVG; every cache hit is served by the web server, which has to add the same two headers itself. Match the extension case-insensitively: the bundle serves logo.SVG as SVG too.

Nginx

The two add_header lines in the location ^~ /_image/ of Public mode:

# http level
map $uri $image_svg_csp { ~*\.svg$ "sandbox"; default ""; }

# server level
location ^~ /_image/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header X-Content-Type-Options "nosniff" always;
    add_header Content-Security-Policy $image_svg_csp always;  # "sandbox" for .svg, empty = not sent otherwise
    try_files $uri /index.php$is_args$args;
}

nosniff goes to every file, Content-Security-Policy: sandbox through the map to SVG only. Keep them in that block: ^~ stops nginx from checking regex locations, so a separate location ~* \.svg$ would never apply and SVG would stay unprotected. The add_header lines do not apply to the fallback response of an SVG that is not cached yet; that one comes from the controller with its own headers.

Apache

Needs mod_headers (a2enmod headers on Debian/Ubuntu).

<LocationMatch "(?i)^/_image/.+\.svg$">
    Header always set Content-Security-Policy "sandbox"
    Header always set X-Content-Type-Options "nosniff"
</LocationMatch>

Caddy

@image_svg path_regexp (?i)^/_image/.+\.svg$
header @image_svg ?Content-Security-Policy "sandbox"
header @image_svg ?X-Content-Type-Options "nosniff"

The ? leaves the first response of an SVG, which comes from PHP with the same two headers, as it is.

Content-Security-Policy: sandbox (with no directive value) applies the strictest sandbox: blocks scripts, forms, popups, plugins, and same-origin access. The SVG still renders as an image. This is cheap (single header in response) and effective against <script> and on* handlers.

If you cannot configure the web server in public mode and SVG hardening is a requirement, sanitize SVGs before they land in the source directory — e.g. using enshrined/svg-sanitize on upload — or use controller mode.

Validating uploaded images

The bundle does not validate uploaded files — that is the host project's job, best done with Symfony's built-in Assert\Image constraint, which already covers size, dimensions, aspect ratio, MIME type, and corruption detection:

use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    #[Assert\Image(
        maxSize: '5M',
        maxWidth: 4000,
        maxHeight: 4000,
        mimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
        detectCorrupted: true,
    )]
    public ?File $image = null;
}

The bundle's max_source_bytes, max_source_pixels and max_width are runtime safety nets, not replacements for proper upload validation: a source above one of the first two answers 413 and nothing is cached — the wrong moment to learn that an upload was too large. Likewise a broken file (text saved as .png, a JPEG cut off before its image data): with autoDimensions or fit="scale-down" the page renders it without height and logs a warning on every render that shows it — on purpose, a broken upload has to show up in the log — and its image URL answers 500.

Image sources

Source images are read from named sources configured under sources. A path without a prefix uses the default source (%kernel.project_dir%/data unless configured); @name/path reads from the source name:

# config/packages/id_sign_image.yaml
id_sign_image:
    sources:
        default: '%kernel.project_dir%/public/uploads'
        reference: '%kernel.project_dir%/assets/reference'
<twig:Image src="uploads/photo.jpg" width="800" alt="From the default source" />
<twig:Image src="@reference/screenshot.png" width="1200" alt="From the reference source" />
{{ image_url('@reference/screenshot.png', 1200, format='webp') }}

The prefix stays part of the path everywhere: in URLs (/_image/%40reference/screenshot.png/…), in the HMAC signature and in the cache directory (public/_image/@reference/screenshot.png/), so variants of @reference/logo.png and logo.png never collide, and image:purge '@reference/screenshot.png' deletes exactly that source's variants. @default/photo.jpg is normalized to photo.jpg on input, so both spellings share one URL and one cache directory.

Source names start with a letter, may contain letters, digits, _ and -, and are case-sensitive. Source paths must be absolute (a %parameter% counts). A path with an unknown source name behaves like a missing file: the page renders without height and blur, the image URL returns 404. Every configured source is a public asset tree — see Security model.

Custom source implementations

Named sources are services implementing ImageSourceInterface; configured paths become LocalFilesystemSource instances. To plug in a custom source (S3, Flysystem, …), tag your service with id_sign_image.source and a name:

use IdSign\ImageBundle\Source\ImageSourceInterface;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('id_sign_image.source', ['name' => 'reference'])]
final class S3ReferenceSource implements ImageSourceInterface
{
    // ...
}

To use a custom implementation as the default source, re-point the id_sign_image.source.default alias:

# config/services.yaml
services:
    id_sign_image.source.default: '@App\Image\S3Source'

Two pre-0.4 ways of configuring the source keep working: overriding the $basePath argument of IdSign\ImageBundle\Source\LocalFilesystemSource still changes the default directory (and takes precedence over sources.default), and replacing the ImageSourceInterface alias with your own service still works but bypasses named sources — your implementation then receives the raw @name/… string.

Cache management

By default, all commands run in dry-run mode (showing what would be deleted). Add --force to actually delete files.

The cache directory must be writable by the web server. If it is not, variants fail (500 for their URLs), pages render without placeholders (the bundle skips making a placeholder it could not cache, with a warning) and without cached dimensions — fix the permissions. A full disk is found only when a write fails; until then each render of a page with blur decodes its sources again.

The cache directory (cache.path, by default the document root plus route_prefix) belongs to the bundle: image:purge and CacheStorageInterface::deleteBySource() delete everything below it, or below the given source, whoever wrote it. Do not put files of your own there. A request that encodes a variant at the very moment a purge empties its directory can fail once; the next request generates the variant again.

Purge all cached images

# Preview
php bin/console image:purge

# Delete
php bin/console image:purge --force

Writing and replacing source files

The bundle assumes a source file appears complete. A page rendered while a JPEG or WebP is half written caches a half-empty variant, its dimensions (meta.json) and its placeholder for good (a half-written PNG is marked broken and tried again after 10 minutes). So:

  • Write sources atomically: into a temporary file in the same directory as the target, then rename() it into place. UploadedFile::move() is atomic only when upload_tmp_dir is on the same filesystem as the target — with /tmp on tmpfs or in a container layer against a bind-mounted data directory, PHP copies and the file grows in place. Then move it to a temporary name in the target directory first and rename it:

    $tmpName = '.upload-'.bin2hex(random_bytes(8));
    $uploadedFile->move($targetDir, $tmpName);
    rename($targetDir.'/'.$tmpName, $targetDir.'/'.$fileName);
  • After replacing a file under the same name, call deleteBySource() (see Programmatic cache invalidation): variants, dimensions and placeholders of the old file are served until then. In public mode that renews only the server's cache: the URL of a variant does not depend on the file's content, and a browser or CDN that has it with immutable keeps the old image for up to a year. Store a replaced image under a new name when visitors must see the change (controller mode revalidates on every view and gets the new variant).

A source that cannot be read (a broken upload) is logged as a warning on every render that shows it, on purpose — see Logging.

Purge a specific source image

php bin/console image:purge uploads/photo.jpg --force

# Variants of an image from a named source
php bin/console image:purge @reference/logo.png --force

# Everything cached below a directory prefix or a whole source
php bin/console image:purge uploads/2024 --force
php bin/console image:purge @reference --force

Tip — upgrading ImageMagick: a new ImageMagick (or new delegate libraries) does not invalidate the cache: variants and placeholders stay as the old version made them, which looks the same. When the change affects colours or formats — typically lcms installed where it was missing (see Colour profiles and metadata) — purge the cache with image:purge --force. The ImageMagick version is deliberately not part of the cache key: every upgrade would make page renders decode the sources again.

Purge by age

# Files not modified in 30 days
php bin/console image:purge --modified-before=30 --force

# Files not accessed in 14 days
php bin/console image:purge --accessed-before=14 --force

# Combine both
php bin/console image:purge --modified-before=30 --accessed-before=14 --force

Both options take a whole number of days, at least 1 — 0 would mean "older than now", i.e. the whole cache; for that, run image:purge --force without them.

Programmatic cache invalidation

Inject CacheStorageInterface to invalidate cache from your application code:

use IdSign\ImageBundle\Cache\CacheStorageInterface;

class ImageUploadHandler
{
    public function __construct(
        private readonly CacheStorageInterface $cacheStorage,
    ) {}

    public function onImageUpdated(string $src): void
    {
        $this->cacheStorage->deleteBySource($src); // e.g. 'uploads/photo.jpg'
    }
}

This deletes all cached variants (all sizes, formats, watermark combinations) for the given source image. In public mode browsers and CDNs keep the variants they already have (immutable, the URL does not change): store a replaced image under a new name, see Writing and replacing source files.

Programmatic URL generation

Generate optimized image URLs from PHP code (e.g. for API responses, emails):

use IdSign\ImageBundle\Service\ImageUrlGenerator;

class ImageApiController
{
    public function __construct(
        private readonly ImageUrlGenerator $imageUrlGenerator,
    ) {}

    public function getImageUrl(Request $request): JsonResponse
    {
        // Negotiate format from Accept header (AVIF > WebP > original)
        $url = $this->imageUrlGenerator->generateFromRequest($request, 'uploads/photo.jpg', 800, 600, 'cover');

        // Or specify a format explicitly: a configured one or the source's fallback, anything else throws
        $url = $this->imageUrlGenerator->generate('uploads/photo.jpg', 800, 600, 'cover', 80, 'webp');

        return new JsonResponse(['image' => $url]);
    }
}

Both methods follow the rules of <twig:Image>: width and height must be between 1 and max_width (an InvalidArgumentException otherwise — the controller trusts the signature, so the cap sits where URLs are made; with fit="cover" a mistyped height of 60000 would scale the source to cover that box before cropping), height is a processing dimension only together with fit (without fit the server resizes by width and keeps the aspect ratio), and a format the controller would not serve throws. quality takes an int or a {format: quality} map like the component attribute; omitted, it is the configured quality of the resulting format (format_quality, then default_quality), resolved after negotiation. Unlike the component, scale-down keeps the requested width instead of the source dimensions, so the URL can be a separate cache variant.

Twig function image_url()

For contexts where you need a single image URL instead of a full <picture> tag — og tags, emails, JSON-LD, etc. For an .svg source it returns the passthrough URL (/_image/icons/logo.svg), like <twig:Image>; the same holds for ImageUrlGenerator. format must be one the controller serves — one of the configured formats or the source's fallback format (see URL security); anything else throws an InvalidArgumentException instead of returning a URL that answers 404. Without format and without a request to negotiate from (console command, e-mail rendered in a worker) the URL is webp, or the source's fallback format when webp is not in formats.

{# Format negotiated from current request (AVIF > WebP > original) #}
{{ image_url('uploads/photo.jpg', 800) }}

{# Explicit format (best for og tags, emails — no content negotiation) #}
{{ image_url('uploads/photo.jpg', 800, format='webp') }}

{# og:image / twitter:image — WebP whatever the source format, see "Share images" below #}
{{ image_url(article.image, 1200, 630, 'cover', format='webp') }}

{# Full control #}
{{ image_url('uploads/photo.jpg', 800, height=600, fit='cover', quality=90, format='avif', watermark='copyright') }}

{# Auto-calculate height from aspect ratio #}
{{ image_url('uploads/photo.jpg', 800, autoDimensions=true, format='webp') }}

Share images (og:image, twitter:image): use format='webp'. As of late 2024 WebP previews render on every major platform — Facebook, X, LinkedIn, Slack, Discord, WhatsApp, iMessage, Threads, Bluesky, Mastodon, Pinterest — while AVIF is dropped by X, LinkedIn, Slack, Discord and iMessage. Do not reach for JPEG out of habit: the controller generates only the configured formats and the source's own format, so format='jpeg' throws for a WebP or PNG source (the gate that keeps one signed URL from producing a lossless PNG, see URL security). If a platform you target really needs JPEG, add jpeg to formats — at the price of a third <source> in every <picture> — and check the result in the Facebook Sharing Debugger and the LinkedIn Post Inspector, which cache previews for days.

src and width are positional and required. Every other parameter is optional and passed by name in any order (Twig named arguments, matching the names in the table), or positionally in the table's order.

Parameter Type Required Description
src string yes Source path, optionally @source/-prefixed
width int yes Output width in pixels
height int no Processing height, 1…max_width, used only together with fit (auto-calculated if autoDimensions enabled)
fit string no cover, contain, or scale-down
quality int|map no Output quality 1-100, or a {format: quality} map applied to the negotiated or given format; omitted: format_quality, then default_quality
format string no A configured format or the source's fallback (jpeg, png, …), else throws. Omitted: negotiated from the request, webp without one
watermark string|false no Profile name, false to disable, omit for global default
autoDimensions bool no Auto-calculate height from aspect ratio (overrides global config)
lossless bool no Lossless encoding for WebP/AVIF output (overrides global config)

Image attributes outside the component (image_attributes())

Everything <twig:Image> renders — <source> types and srcset, src, width, height, sizes, the placeholder — is decided in one service, ImageAttributesResolverInterface, which the component uses itself. Use it where the markup is built elsewhere: images inserted by Alpine or other client code, a JSON API, a CSS background. HTML that htmx swaps in is rendered on the server, so the component works there as it is.

image_attributes() takes the component's props by the same names, plus sizes and loading, and returns an ImageAttributes object (src, width, height, sizes, sources, placeholder, placeholderStyle, attributes). |json_encode gives:

{
  "src": "/_image/uploads/photo.jpg/2b2e…_640_auto_none_80.jpeg",
  "width": 640,
  "height": 480,
  "sizes": "100vw",
  "sources": [
    {"type": "image/avif", "srcset": "/_image/uploads/photo.jpg/f1db…_320_auto_none_80.avif 320w, … 640w"},
    {"type": "image/webp", "srcset": "/_image/uploads/photo.jpg/5080…_320_auto_none_80.webp 320w, … 640w"}
  ],
  "placeholder": "data:image/jpeg;base64,/9j/4AAQ…",
  "placeholderStyle": {
    "background-image": "url(\"data:image/jpeg;base64,/9j/4AAQ…\")",
    "background-size": "cover",
    "background-position": "center",
    "background-repeat": "no-repeat",
    "background-clip": "content-box",
    "background-origin": "content-box"
  },
  "attributes": {"decoding": "async", "data-blur-placeholder": ""}
}

placeholder is null and placeholderStyle empty without one, attributes holds the further <img> attributes (data-blur-placeholder only with a placeholder). For an SVG source sources is empty and sizes is null, like the component renders it.

Alpine (or any client code): set the placeholder property by property — el.style.setProperty() for each entry of placeholderStyle — not by concatenating style text (:style="'background-image:…' + …"): a property takes one value, so nothing in the data can append another declaration. Set data-blur-placeholder together with it (it is in attributes) — the script for transparent sources finds images by it. Keep width and height on the inserted <img>; a sizes of auto, … works only with loading="lazy" and a height with the real aspect ratio of the file.

<div x-data="{ image: {{ image_attributes(product.image, 640, autoDimensions: true, blur: true, loading: 'lazy')|json_encode|e('html_attr') }} }">
    <picture>
        <template x-for="source in image.sources">
            <source :type="source.type" :srcset="source.srcset" :sizes="image.sizes">
        </template>
        <img :src="image.src" :width="image.width" :height="image.height" :sizes="image.sizes" alt="" loading="lazy"
             x-init="
                 Object.entries(image.attributes).forEach(([name, value]) => $el.setAttribute(name, value));
                 Object.entries(image.placeholderStyle).forEach(([property, value]) => $el.style.setProperty(property, value));
             ">
    </picture>
</div>

JSON API: the object is JsonSerializable, so a controller returns it as it is:

use IdSign\ImageBundle\Service\ImageAttributesResolverInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

public function product(Product $product, ImageAttributesResolverInterface $images): JsonResponse
{
    return new JsonResponse([
        'name' => $product->getName(),
        'image' => $images->resolve($product->getImage(), 640, autoDimensions: true, blur: true),
    ]);
}

CSS background (image-set()): a background picks a candidate by type and pixel density, not by width, so it gets one width per format — build it from image_url():

{% set src = 'uploads/hero.jpg' %}
<section style="background-image: image-set(
    url('{{ image_url(src, 1920, format: 'avif') }}') type('image/avif'),
    url('{{ image_url(src, 1920, format: 'webp') }}') type('image/webp'),
    url('{{ image_url(src, 1920, format: 'jpeg') }}') type('image/jpeg'))">

Placeholder alone: image_placeholder(src) returns the placeholder of a source — whatever blur.enabled says — or null (SVG, a missing, unreadable or oversized source, a transparent one unless blur.transparent); it prints as its data URI. A custom generator applies here too:

{% set placeholder = image_placeholder('uploads/hero.jpg') %}
<section {% if placeholder %}style="background-image: url('{{ placeholder }}'); background-size: cover"{% endif %}>

Changing the output for the whole application: decorate ImageAttributesResolverInterface. The component template renders from nothing but the returned object, so one decorator changes <twig:Image>, image_attributes() and your PHP callers alike — per request, route or source. ImageAttributes is immutable; withSizes(), withPlaceholder() and withAttribute() return a changed copy (the data-blur-placeholder attribute follows the placeholder; names the component renders itself — src, width, height, sizes, srcset, style — are refused). Attributes given on <twig:Image> override the decorator's, except class, data-controller and data-action, which ux-twig-component joins. image_placeholder() reads the placeholder generator directly and does not pass through the decorator.

use IdSign\ImageBundle\Service\ImageAttributes;
use IdSign\ImageBundle\Service\ImageAttributesResolverInterface;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;

#[AsDecorator(ImageAttributesResolverInterface::class)]
final class ProductImageAttributes implements ImageAttributesResolverInterface
{
    public function __construct(#[AutowireDecorated] private readonly ImageAttributesResolverInterface $inner)
    {
    }

    public function resolve(string $src, int $width, ?int $height = null, ?string $fit = null, int|array|null $quality = null,
        string|false|null $watermark = null, ?bool $lossless = null, ?bool $autoDimensions = null, ?bool $blur = null,
        ?string $sizes = null, ?string $loading = null): ImageAttributes
    {
        $attributes = $this->inner->resolve($src, $width, $height, $fit, $quality, $watermark, $lossless, $autoDimensions, $blur, $sizes, $loading);

        return str_starts_with($src, '@products/') ? $attributes->withAttribute('data-product-image', '') : $attributes;
    }
}

ImageAttributesResolverInterface and ImageAttributes are public API from 0.6: a change that breaks a decorator or a caller comes only with a minor version and an entry in UPGRADE.md; ImageAttributes may gain fields.

Logging

The bundle logs warnings — a source that cannot be read, an ICC profile that cannot be converted to sRGB — through PSR-3 to the Monolog channel id_sign_image (without MonologBundle the default logger service is used, if any). Route it like any other channel, for example into its own file and out of the main log:

# config/packages/monolog.yaml
monolog:
    handlers:
        images:
            type: stream
            path: '%kernel.logs_dir%/images.log'
            level: warning
            channels: ['id_sign_image']
        main:
            # ...
            channels: ['!id_sign_image']

The channel needs no entry in monolog.channels; the bundle registers it.

Development warnings

With kernel.debug (the dev environment) the component also logs a warning — visible in the profiler's Logs panel, channel id_sign_image — when an image renders but costs bandwidth or layout stability:

  • loading="lazy" with fetchpriority="high": a lazy image waits for layout, so the priority is lost. The main image of the page gets fetchpriority="high" without loading="lazy".
  • A height the file does not get — without fit, or with contain/scale-down over a larger source — whose ratio differs from the source by more than 1 px: the layout shifts once the image loads (with sizes="auto" the image is distorted). Use autoDimensions, the source ratio, or fit="cover".
  • No sizes where the bundle cannot use auto (not lazy, or the aspect ratio unknown), no decorator of the resolver set one, and srcset offers more than one candidate: the browser downloads the candidate for the full viewport width.

The height check reads the source dimensions (and writes meta.json) even where production would not — development does a bit more I/O on the first render. In production nothing is checked.

Upgrading

See UPGRADE.md for what to check or change when you upgrade from an earlier version — breaking changes, configuration that now fails the container build, and cache entries to purge.

Development

# Install dependencies
composer install

# Run tests
vendor/bin/phpunit

# Static analysis
vendor/bin/phpstan analyse

# Code style fix
vendor/bin/php-cs-fixer fix

Docker test matrix

Run tests across all supported PHP versions using Docker:

make test-matrix           # Run tests on PHP 8.2, 8.3, 8.4, 8.5
make test                  # Run tests on PHP 8.4 (default)
make test PHP_VERSION=8.2  # Run tests on a specific PHP version
make phpstan               # Run PHPStan analysis
make cs-fix                # Run PHP CS Fixer (dry-run)

License

MIT

resources/sRGB2014.icc is the International Color Consortium's sRGB profile (Copyright International Color Consortium, 2015), distributed under the ICC's terms: it may be copied, distributed, embedded, made, used, and sold without restriction; altered versions must have the original identification and copyright information removed. resources/AdobeCompat-v2.icc (an Adobe RGB-compatible profile) and the ICC profiles embedded in the test fixtures tests/Fixtures/p3.jpg and tests/Fixtures/srgb-tagged.jpg come from Compact-ICC-Profiles (CC0 1.0).