The bundle is called id-sign/image-bundle. The aim was a lightweight but powerful library. It is freely available under the MIT licence and we use it in our own projects too.
In short
- One component:
<twig:Image>renders a<picture>with AVIF and WebP sources,srcset,sizesand a placeholder. From it the browser downloads a variant in the size that screen needs. - No PHP after the first request: a variant lies on disk under its own URL and the web server sends it by itself.
- Signed URLs: width, height, crop and quality can be anything on each image, and an attacker cannot make new variants.
- Watermark: the bundle adds it to every variant according to a named profile with an image, position and opacity. Editing the URL does not remove it.
- Placeholder in the HTML: a small JPEG inlined as a data URI, so it shows together with the page. For any source, including files uploaded at runtime.
sizes="auto"by default: a lazy image downloads the variant for the width it is actually rendered at.- The same outside the component: everything
<twig:Image>renders (srcset,sizes, dimensions, preview) is also available, with the same parameters, from Twig functions and from PHP. Useful for a JSON API, Alpine.js or a CSS background. - Access control: in
controllermode every image request goes through the Symfony firewall. - Extensible through interfaces: your own sources, cache, processing, preview and HTML output.
- A skill for AI agents ships with the package.
Installation and the first image
The bundle needs the PHP extension imagick. Its other dependencies are Symfony components and Symfony UX Twig Components, which Composer installs on its own. It needs no external tool or service to process images.
composer require id-sign/image-bundle
Add its routes to config/routes/id_sign_image.yaml:
id_sign_image:
resource: '@IdSignImageBundle/config/routes.yaml'
By default, source images are read from the data/ directory; further sources are named in the configuration. Then render an image with the component:
<twig:Image src="uploads/photo.jpg" width="800" height="600" alt="Photo" />
Output:
<picture>
<source type="image/avif"
srcset="/_image/uploads/photo.jpg/b152d75a7b720434_320_auto_none_80.avif 320w,
/_image/uploads/photo.jpg/96e59291da55ab44_480_auto_none_80.avif 480w,
/_image/uploads/photo.jpg/31e03189729eb89b_640_auto_none_80.avif 640w,
/_image/uploads/photo.jpg/9bf64e52b9ec020c_750_auto_none_80.avif 750w,
/_image/uploads/photo.jpg/da08aa435f2567a2_800_auto_none_80.avif 800w"
sizes="100vw">
<source type="image/webp"
srcset="/_image/uploads/photo.jpg/b152d75a7b720434_320_auto_none_80.webp 320w,
/_image/uploads/photo.jpg/96e59291da55ab44_480_auto_none_80.webp 480w,
/_image/uploads/photo.jpg/31e03189729eb89b_640_auto_none_80.webp 640w,
/_image/uploads/photo.jpg/9bf64e52b9ec020c_750_auto_none_80.webp 750w,
/_image/uploads/photo.jpg/da08aa435f2567a2_800_auto_none_80.webp 800w"
sizes="100vw">
<img src="/_image/uploads/photo.jpg/da08aa435f2567a2_800_auto_none_80.jpeg"
width="800" height="600" sizes="100vw" decoding="async" alt="Photo">
</picture>
width is the width of the largest file, not the width in CSS. The bundle takes the smaller srcset candidates from the device_sizes list of widths in the configuration: every width below width, plus width itself. If you do not set the list, the default 320, 480, 640, 750, 828, 1080, 1200, 1920, 2048 and 3840 px applies. That is why width="800" gave the widths 320 to 750 and 800. You can change the list for the whole application:
# config/packages/id_sign_image.yaml
id_sign_image:
device_sizes: [400, 800, 1200, 1600, 2400]
The browser picks the smallest candidate that covers the image's width on the page times the display density. A phone downloads a small variant, a high-resolution monitor a large one. Each variant is made on the first request and then stays in the cache. So the bundle takes care of both format and size by itself: the template only needs the dimensions, with no complex configuration.
Multiple image sources
Images can also be read from directories other than data/. Name each one in the configuration and refer to it in src with the prefix @name/:
# config/packages/id_sign_image.yaml
id_sign_image:
sources:
default: '%kernel.project_dir%/data'
reference: '%kernel.project_dir%/assets/reference'
<twig:Image src="@reference/screenshot.png" width="1200" alt="…" />
A path without a prefix is read from the default source. The prefix stays part of the variant's URL (/_image/%40reference/screenshot.png/…), of the signature and of the cache directory. So the variants of logo.png and @reference/logo.png never mix, and image:purge '@reference/screenshot.png' --force deletes exactly the variants of that file. This suits images kept in git next to the templates, for instance, while files uploaded in the admin live in data/.
The browser picks the format, not the server
Next Image sends every image through the /_next/image endpoint. It picks one format from the Accept header and marks the response Vary: Accept. One URL therefore holds different files for different browsers.
The bundle does not negotiate the format. It renders a <picture> with <source type="image/avif"> and <source type="image/webp"> and the browser picks by itself. Each URL means exactly one file in one format.
So the file lies on disk under a path that matches the URL. The web server finds and sends it without PHP; PHP is called only on the first request for a variant. Configurations for Nginx, FrankenPHP and Caddy follow below, the one for Apache is in the README.
Caches and CDNs do not have to handle Vary. A layer that ignores Vary: Accept could send AVIF from a negotiated URL to a browser that cannot show it. That cannot happen here. The fallback format follows the source: <img> gets JPEG for a JPEG, PNG for a PNG.
For Nginx this is enough:
# at http level
map $uri $image_svg_csp {
~*\.svg$ "sandbox";
default "";
}
location ^~ /_image/ {
try_files $uri /index.php$is_args$args;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy $image_svg_csp;
}
^~ tells Nginx not to try regex locations for URLs starting with /_image/. Those take precedence otherwise. If the configuration had, say, location ~* \.(webp|avif|jpe?g|png)$ with a long expires for static files, it would handle the variant URLs too. It would end a missing variant with a 404 without calling PHP, so the variant would never be made.
FrankenPHP needs nothing extra. php_server first looks for an existing file and only then passes the request to index.php. This website runs the same way:
:80 {
root * /app/public
@image path /_image/*
header @image ?Cache-Control "public, max-age=31536000, immutable"
@imageSvg path_regexp (?i)^/_image/.+\.svg$
header @imageSvg {
?Content-Security-Policy "sandbox"
?X-Content-Type-Options "nosniff"
}
php_server
}
Caddy with PHP-FPM needs file_server next to php_fastcgi. php_fastcgi finds the file but does not send it, so without file_server every finished variant would come as an empty 200 response:
example.com {
root * /var/www/app/public
@image path /_image/*
header @image ?Cache-Control "public, max-age=31536000, immutable"
@imageSvg path_regexp (?i)^/_image/.+\.svg$
header @imageSvg {
?Content-Security-Policy "sandbox"
?X-Content-Type-Options "nosniff"
}
php_fastcgi unix//run/php/php-fpm.sock
file_server
}
The web server sends a finished variant, so it has to set the caching header itself. PHP sends it only on the first request. The URL carries the path and the conversion parameters, so the file never changes under the same URL and can be immutable for a year. The header belongs to files from disk only. Nginx does not apply it from the /_image/ location to a PHP response by itself. Beware, though, that add_header in a location cancels every add_header from the server block, so you have to repeat the security headers from there in the /_image/ location. In Caddy the ? takes care of it: it sets the header only when the response does not have one yet. A 403 or 404 from the bundle thus keeps its no-cache. For SVG the examples also add Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff (the Security section explains why). Through map, Nginx sends sandbox only for SVG and leaves the header out when the value is empty. In Caddy the ? prevents doubled headers, since PHP sends them too on the first request for an SVG.
Behind Traefik or another reverse proxy nothing changes: the proxy only forwards requests and the server behind it finds the file.
Signed URLs instead of a list of allowed widths
An endpoint that resizes images by parameters in the URL can be abused. Whoever sends a thousand different widths makes the server decode the source a thousand times and fills the disk.
Next Image defends itself with lists: the width must come from deviceSizes or imageSizes and the quality from qualities. The endpoint rejects other values with a 400. The component pulls a quality outside the list to the closest allowed one, with a warning in development and silently in production. So quality={90} without a configuration change comes out as 75. The URL carries no height, crop or anything else.
The bundle signs every raster image URL with HMAC-SHA256 under a key derived from kernel.secret. The signature is part of the path, and changing any parameter ends with a 403. Only URLs made by the application are valid, so width, height and quality can differ on every image.
The format is not part of the signature; one signature covers every <source> of a width with the same quality. The controller therefore makes only the configured formats and the source's fallback format, and any other extension gets a 404.
Images for authorised users only
The signature protects against making variants, not against who sees the image. In the default public mode the web server sends finished variants straight from public/ and the Symfony firewall never sees the request. Whoever knows the URL downloads the image.
Next Image has no access control. The default loader forwards no headers when it fetches the source, so it cannot load an image behind a login, and the documentation advises turning optimization off for such images (unoptimized). In our test the endpoint answered 401 for a protected source even though the request carried the cookie. And a source with Cache-Control: private came out of the endpoint as public.
For client documents, photos in an admin or images in a customer area the bundle has controller mode. Every image request then goes through PHP and the firewall, even one for a variant that is already cached:
# config/packages/id_sign_image.yaml
id_sign_image:
serve_mode: 'controller'
cache:
ttl: 86400
path: '%kernel.project_dir%/var/image-cache'
# config/packages/security.yaml
security:
access_control:
- { path: ^/_image, roles: ROLE_USER }
The cache must live outside public/. Otherwise try_files finds it and sends it without PHP: the first authorised visitor would fill the cache and everyone after them would get the file unchecked. Always set the mode to controller as well, because the bundle picks the caching headers by serve_mode, not by where the cache lives. cache.ttl sets how long a variant is valid. After that it is made again from the source.
Access to individual images
The bundle's controller checks the signature and the firewall the role, but neither knows who may see a particular file. When only the owner of a document should see an image, say, add a kernel.request listener with the default priority on the id_sign_image route. It runs after the router and the firewall, so it knows the route and the logged-in user. A custom source (ImageSourceInterface) that "does not find" the file for some users is not enough, because a cached variant is sent without asking the source.
The route's path attribute starts with the source path. Your voter for IMAGE_VIEW decides by it, for example by finding the document and comparing the owner. Without the permission the listener returns a 403; otherwise the bundle's controller sends the image as usual:
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
#[AsEventListener]
final class ImageAccessListener
{
public function __construct(private readonly Security $security)
{
}
public function __invoke(RequestEvent $event): void
{
$request = $event->getRequest();
if ('id_sign_image' !== $request->attributes->get('_route')) {
return;
}
// "documents/42/scan.jpg/<signature>_640_auto_none_80.webp": the source is everything before the last slash
$source = \dirname($request->attributes->getString('path'));
if (!$this->security->isGranted('IMAGE_VIEW', $source)) {
throw new AccessDeniedHttpException();
}
}
}
Browsers, shared caches and CDNs
The controller sends Cache-Control: private, no-cache and Last-Modified. Neither a CDN nor a reverse proxy stores a protected image, whether the firewall uses the session or is stateless, for example with a token in a cookie. The browser asks on every view, so revoked access and a logout on a shared computer take effect at once. An unchanged variant costs a 304 response without the file. Keep CDN rules that cache everything regardless of Cache-Control away from image URLs.
If you use controller mode only for cache.ttl, with no access control, a response listener from the README puts the images back into the CDN. It works only while nothing on the image route uses the session, such as a firewall that logs in through the session or a listener that reads the locale from the session. Symfony then turns the response back to private and the CDN does not store it.
Letting the web server send the file
In controller mode PHP sends the file. With X-Accel-Redirect (Nginx, FrankenPHP) or X-Sendfile (Apache) PHP answers with a header only and the web server sends the file, while access control still runs. The bundle uses the standard BinaryFileResponse for this. Symfony has to trust the X-Sendfile-Type header, though, and the web server has to know the mapping of the cache directory:
# config/packages/framework.yaml
framework:
trust_x_sendfile_type_header: true
# at http level
map $uri $image_svg_csp {
~*\.svg$ "sandbox";
default "";
}
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;
}
The path in the mapping must be the absolute cache.path with symlinks resolved, so with a deployment through a current -> releases/42 symlink (Deployer, Capistrano) the release path. A wrong mapping reports nothing and PHP keeps sending the file. An ETag header shows the hand-over works: the web server sends it, a response from PHP has none. Nginx drops the SVG security headers the controller sends during the hand-over. That is why the example adds them again in the internal location, Content-Security-Policy only for SVG through map. Configurations for FrankenPHP and Apache are in the README.
Height and crop
Next Image changes only width and quality; cropping is done in CSS with object-fit. The bundle handles the height too:
fit="cover"fills the size and crops what sticks out. The crop is always centred; set another area in CSS withobject-position.fit="contain"fits the image into the size and keeps the aspect ratio.fit="scale-down"works likecontainbut never enlarges a smaller source. Thewidthandheightattributes then match the real file.- Without
fitheightis only an attribute that reserves space, and the server resizes by width.
Templates usually do not know the dimensions of uploaded files. The autoDimensions attribute computes the height itself:
<twig:Image :src="article.image" width="800" autoDimensions loading="lazy" alt="…" />
The bundle reads the source dimensions from the file header, without decoding the image, and stores them in the cache next to the variants. It computes the height from the source's aspect ratio, so a 1600 × 1200 landscape photo gets height="600". For a photo rotated only by its EXIF data it uses the dimensions after rotation. The browser reserves the right space, the page does not jump once the image loads, and a lazy image gets sizes="auto". Without autoDimensions the height would be missing and sizes would stay 100vw. When the source is missing or broken, no height is written and the page still renders. Switch the calculation on for the whole application with auto_dimensions: true in the configuration, and off for a single image with :autoDimensions="false". It applies only where you leave out height.
The bundle also has lossless WebP and AVIF (lossless) and quality per format, because AVIF looks like WebP at a lower number:
<twig:Image src="uploads/hero.jpg" width="1920" height="800" fit="cover" :quality="{avif: 55, webp: 75}" alt="…" />
Watermark
The bundle adds a watermark to every variant itself, according to a named profile. You set up the profile with the watermark image in the configuration and pick it by name in the template:
# config/packages/id_sign_image.yaml
id_sign_image:
watermarks:
copyright:
path: '%kernel.project_dir%/assets/watermark.png'
position: bottom-right
opacity: 50
size: 20
margin: 10
<twig:Image :src="photo.image" width="1200" autoDimensions watermark="copyright" alt="…" />
Size (size) is a percentage of the variant's width. The watermark is added to the already resized image, so it covers the same share of the image at every width in the srcset. Make the watermark image at least as wide as it will be in the largest variant, a smaller one gets enlarged. On a wide crop the watermark always fits the variant's height including the margins, nothing of it is cut off. The margin (margin) is in pixels and does not change with the width, but it is at most a quarter of the variant's side. Position (position) is one of nine: the corners, the middles of the edges and the centre. The watermark image is usually a PNG with transparency, opacity (0–100) makes it more transparent still.
The template only picks the profile. The watermark attribute takes a profile name, or false for an image without a watermark. Position, size and opacity cannot be set on the component, for a different placement add another profile to the configuration. For the whole site set the profile with default_watermark.
Editing the URL will not remove the watermark. The profile name is in the variant's URL (…_80_wm-copyright.webp) and in its signature, a URL without it ends with a 403. It only protects images whose source is not in the site's public directory, where the original could be downloaded, and where no template or code renders the same source without a watermark (:watermark="false") or with another profile. Such a variant has its own validly signed URL.
When you replace the watermark image, give it a profile with a new name. The URL carries the name, not the file's content, so the finished variants with the old watermark would keep being sent, in browsers even after the cache is cleared because of immutable. With a new name the variants get new URLs and are generated again.
Colours and orientation
iPhone photos are in Display P3, cameras can shoot Adobe RGB and screenshots carry the monitor profile. The bundle converts every source with an ICC colour profile to sRGB and only then strips the metadata, so the colours stay as the author saw them. It applies the EXIF orientation before it drops the EXIF block, so portrait photos are not rotated.
LittleCMS does the conversion through ImageMagick. When ImageMagick lacks the lcms delegate, profiled sources are logged and sent unconverted, with washed-out colours. Check it with magick -list configure | grep DELEGATES, or convert -list configure | grep DELEGATES on ImageMagick 6.
A placeholder until the image loads
A placeholder fills the image's place with the photo's colours before it downloads. The page does not look empty and nothing jumps.
Next Image makes one automatically only for images imported in code, at build time. It renders it as an SVG with a feGaussianBlur filter in the background of <img> and removes it with a script once the image has loaded. For images from another server or uploaded at runtime the developer has to supply blurDataURL.
In the bundle the blur attribute is enough, for any source:
<twig:Image :src="product.image" width="1200" height="600" fit="cover" blur loading="lazy" alt="…" />
The preview is made on the first render of a page with the image and cached next to the variants. The blur is in the bitmap itself:
- the source is shrunk to 10 px on its longer side,
- enlarged four times with a Gaussian filter and blurred,
- saved as a JPEG at quality 90 without chroma subsampling and inlined into
styleas a data URI.
The browser shows the bitmap from the data URI at once and stretches it as a background, with no JavaScript. The referenced image covers it once loaded. It would show through a transparent image, though, so the bundle does not create it for transparent sources. A single transparent pixel is enough to make a source transparent; typically these are product photos on a transparent background. You can allow it in the configuration with blur.transparent: true, but the application then has to hide it with its own JavaScript once the image loads. A ready-made script is in the README, and the skill describes the steps too. An image with the background automatically has the data-blur-placeholder attribute for your scripts and CSS to rely on.
The bitmap replaces an SVG filter for a reason: the filter has a cost. The browser rasterises it at the element's size and recomputes it on repaint. Next removes it after loading, but without JavaScript it would stay for good. A blurred bitmap costs nothing at render time.
The bundle uses quality 90 without subsampling because the bitmap is stretched about 25×. At lower quality the JPEG blocks then show as blotches, and subsampled chroma (4:2:0) shifts the colours. Lossy WebP is always subsampled. In our test the preview cost about 330 B of HTML per landscape photo after gzip, the SVG from Next about 270 B. A listing of twenty photos thus adds a few kilobytes of HTML.
The preview needs style-src 'unsafe-inline' and img-src data: in the CSP. Without them the browser drops it and the image renders as usual, sharp. We checked this in Chrome, Firefox and WebKit. A broken source does not bring the page down: a truncated upload or text with a .png extension renders without a preview and a warning goes to the log.
With object-fit: contain in a box of another aspect ratio, blurred bars remain next to the image, because the background fills the whole element. The preview belongs with fit="cover" or a box with the image's aspect ratio.
A custom preview, a single dominant colour say, comes from your own PlaceholderGeneratorInterface. The generator returns the image data and type and the bundle builds the data URI. Not even a custom generator can slip anything other than an image into the style attribute.
sizes="auto" by default
The sizes attribute tells the browser how wide the image will be. Without it the browser assumes the full window width and an image in a column downloads needlessly large.
For an image with a fixed width and no sizes, Next Image writes a srcset with the densities 1x, 2x; with sizes, width candidates; and for fill without sizes it adds 100vw. The bundle always writes width candidates and adds sizes="auto, 100vw" to lazy images. A browser that supports auto measures the width only at layout. Chrome, Firefox and Safari support it; older browsers use the value after the comma, 100vw. In our test in Chrome an image in a 400 px column on a 1280 px window downloaded the 480w variant with auto and the 1280w variant with 100vw.
The bundle adds auto only where it is safe:
- Only with
loading="lazy". Browsers do not use it for other images. - Only when it knows the real aspect ratio of the file:
fit="cover"with a height, a height computed from the source (autoDimensions), orscale-downwhere the source fits the box. A browser takes the aspect ratio of an image withsizes="auto"from thewidthandheightattributes alone. A height of another ratio would distort the image. - Only when
srcsethas more than one candidate. With a single one there is nothing to pick.
auto is a safety net for a forgotten sizes, not a replacement. Give images that do not span the full width a sizes matching the real layout. Take a product grid: content at most 1200 px wide, 16 px margins on each side, 24 px gaps between columns, one column on a phone, two from 640 px and three from 1024 px:
<twig:Image src="uploads/product.jpg" width="1200" height="900" fit="cover" loading="lazy" alt="…"
sizes="(min-width: 1232px) 384px,
(min-width: 1024px) calc((100vw - 80px) / 3),
(min-width: 640px) calc((100vw - 56px) / 2),
calc(100vw - 32px)" />
The browser reads the conditions from the left and uses the first one that matches. The value without a condition at the end covers everything else. The values are image widths in CSS pixels or vw; margins and gaps are subtracted with calc(). sizes does not accept percentages.
From 1232 px (1200 + 2 × 16) the content has its full width and a column is (1200 − 2 × 24) / 3 = 384 px. From 1024 px it is the window width minus the margins (32 px) and two gaps (48 px), divided by three, and from 640 px the same for two columns with one gap. On a phone it is the window width minus the margins.
width="1200" covers even a phone with a triple-density display. In our test Chrome downloaded with this sizes:
- a 390 px phone with density 3: the 1080w variant (1074 px needed),
- a 1440 px monitor with density 2: 828w (768 px needed),
- a 1440 px monitor with density 1: 480w (384 px needed).
With sizes="100vw" it downloaded 1200w in all three cases, so on an ordinary monitor a file two and a half times wider than needed.
The main image of the page (LCP) gets fetchpriority="high" and never loading="lazy", because a lazy image waits for layout. Next has a preload prop for it that adds <link rel="preload">. The bundle deliberately has none: the browser's preload scanner finds the main image's srcset by itself, and a preload would target only one format.
Defaults and exceptions
Most options from the previous chapters are set in the configuration as defaults for the whole application, and the component attribute of the same name overrides them for a single image. The copyright profile is the one from the Watermark chapter:
# config/packages/id_sign_image.yaml
id_sign_image:
default_quality: 80
format_quality: { avif: 55, webp: 75 }
lossless: false
auto_dimensions: true
blur:
enabled: true
default_watermark: copyright
<twig:Image src="docs/screenshot.png" width="1200" lossless :blur="false" :watermark="false" alt="…" />
The screenshot thus comes out lossless, without a preview and without a watermark, even though the site has them switched on otherwise.
The quality attribute overrides default_quality and format_quality. A number (quality="90") applies to every format, a map (:quality="{avif: 70}") only to the formats it names, the others stay as configured.
lossless, autoDimensions and blur are switched on by the bare attribute and off by an expression with a colon, such as :blur="false". Without the attribute the configuration decides. The colon matters: blur="false" is text and means on. watermark takes a profile name, or likewise :watermark="false".
The list of widths device_sizes, the formats, limits such as max_width and the cache settings stay in the configuration only.
Everything is available from PHP too
Next has getImageProps(), which returns attributes for your own <picture> or a background, but without a preview. In the bundle everything the component renders is decided by one service, ImageAttributesResolverInterface. The component uses it itself, and you get the same result outside it:
image_attributes()in Twig returns an object withsources,src,width,height,sizes, the preview and further attributes. Through|json_encodeyou hand it to Alpine.js or other code in the browser.- In PHP
resolve()returns the same object and a JSON response serialises it. image_url()returns one URL forog:image, e-mails, JSON-LD or a background throughimage-set().image_placeholder()returns just the source's preview.
public function product(Product $product, ImageAttributesResolverInterface $images): JsonResponse
{
return new JsonResponse([
'name' => $product->getName(),
'image' => $images->resolve($product->getImage(), 640, autoDimensions: true, blur: true),
]);
}
When JavaScript in the browser builds the image from data, set the preview property by property with el.style.setProperty(), not by concatenating style text, and set the data-blur-placeholder attribute along with it. An example is in the README. HTML rendered on the server, including HTML inserted into the page later, gets the component unchanged.
When you need to change the output for the whole application, for example add an attribute to images from one source or compute sizes differently, decorate ImageAttributesResolverInterface. The component template renders from the returned object alone, so one decorator changes the component, image_attributes() and PHP callers at once.
Extensibility
The bundle is not extended through configuration switches but through interfaces. Each part has one place that can be replaced or decorated with a Symfony service:
ImageSourceInterface: where sources are read from. Tag a custom source (S3, Flysystem) withid_sign_image.sourceand a name, and refer to it in templates with the prefix@name/path.CacheStorageInterface: where variants, dimensions and previews are stored.ImageProcessorInterface: how an image is resized, cropped and encoded.PlaceholderGeneratorInterface: what the preview looks like. Source size checks, caching and building the data URI stay in the bundle, so a custom generator does not have to repeat them.ImageAttributesResolverInterface: what goes into HTML and JSON. One decorator changes the component,image_attributes()and PHP callers.- Logs go to the Monolog channel
id_sign_image. You can send them to their own file, silence them or turn them into alerts.
A new configuration option appears only where switching something on needs cooperation outside PHP, such as blur.transparent, which needs a script in the browser to hide the preview. Other changes in behaviour are a decorator you write to fit.
The cache and clearing it
By default Next stores optimised images in .next/cache/images, separately on each instance. A custom cacheHandler with images.customCacheHandler can share the cache between instances. A variant is valid for minimumCacheTTL (4 hours by default) or the source's max-age, whichever is longer, and is then refreshed. Before that, according to the documentation, only deleting the directory or changing src invalidates it. In our test the old variants kept coming after the source was overwritten; only widths not yet in the cache showed the new image.
The bundle keeps variants on disk and deletes them with a command or from code:
php bin/console image:purge uploads/photo.jpg --force
php bin/console image:purge --accessed-before=14 --force
From code, call CacheStorageInterface::deleteBySource() after replacing a file. Otherwise the variants, dimensions and preview of the old file keep being sent. In browsers, though, a file replaced under the same name does not show because of immutable, not even after the cache is purged. Store a new image under a new name.
Write sources atomically: into a temporary file in the same directory, then rename(). A page rendered in the middle of a write would otherwise cache a half-empty variant. UploadedFile::move() is atomic only when the upload temp directory is on the same filesystem as the target. With /tmp in memory or in a container layer, PHP copies the file and the write is no longer atomic.
In controller mode variants also expire with cache.ttl (see Images for authorised users only).
Hints during development
In the dev environment the bundle writes warnings to the id_sign_image channel, so you see them in the profiler:
loading="lazy"together withfetchpriority="high",- a height with another aspect ratio than the source, which shifts the page once the image loads (CLS),
- a missing
sizeswhere the bundle cannot useauto.
Only the browser knows which image is the main image of the page. Measure that in Lighthouse or DevTools.
Security
In public mode the source directory is public. Every file you render is reachable. SVG is not signed, so every SVG in the directory is reachable. Files with controlled access belong in controller mode behind the firewall (above).
max_source_bytes and max_source_pixels protect against decompression bombs. They reject a source by file size and by the pixel count in its header before Imagick decodes it. A highly compressed 100 MP image is about 15 MB, but decoded it needs over a gigabyte of memory. Set up ImageMagick's policy.xml too. The bundle's limits are a safety net, though, not a check at upload time: validate uploads with the Assert\Image constraint.
SVG passes through unchanged. The controller sends it with Content-Security-Policy: sandbox and X-Content-Type-Options: nosniff. In public mode the web server answers later requests, so it has to add the same headers. The examples for Nginx, FrankenPHP and Caddy in the section The browser picks the format, not the server include them; the configuration for Apache is in the README.
What the bundle does not do
- Animation: an animated GIF, APNG or WebP is processed from its first frame. Serve an animation as a plain file outside the component.
- Crops anywhere but the centre. Handle the visible area in CSS.
- Nothing without Imagick. AVIF also needs an encoder for libheif (the
libheif-plugin-aomencpackage on Debian and Ubuntu). - The first render costs more. A preview needs the source decoded: tens of milliseconds for a JPEG photo, up to a second for a 12–24 MP PNG or HEIC. A listing of dozens of large sources can hit
max_execution_timeafter a deployment or a bulk import. Open such pages before the visitors do.
Guide for AI agents
The package ships a skill for AI agents in the Agent Skills format: vendor/id-sign/image-bundle/.claude/skills/image-bundle/SKILL.md. It is a condensed README: the component's attributes, how to choose width and sizes, when to use autoDimensions and fit="scale-down", the preview, the modes, the interfaces and what changes when moving to a newer version. With it an agent reaches for the bundle's existing option instead of solving dimensions or upscaling with code of its own.
Neither Claude Code nor Codex reliably loads a skill from vendor/ by itself, though. Copy it into the project's .claude/skills/, or point to it from AGENTS.md or CLAUDE.md with a sentence like "read … before working with images". Next to it lies the bundle's CLAUDE.md with the rules for developing the bundle itself. It is useful when you want to contribute.
Links: id-sign/image-bundle on GitHub, Packagist, Next Image in the Next.js documentation, sizes="auto" on MDN.