Image resolution

Check that each image's resource resolution matches its painted size

View on GithubNew to Storybook?Get started

Image resolution

CI npm version License: MIT

storybook-addon-image-resolution is a Storybook addon that checks whether each image in a story is sharp without being wasteful: it compares the resolution of the image file the browser actually chose with the size the image is painted at, on the current screen.

  • Undersized images look blurry: the file has fewer pixels than the screen shows.
  • Oversized images waste bandwidth: the file has more pixels than the screen can show.

100% is a match. The comparison is per axis and uses the screen's real device pixel ratio (DPR), so a 400 px wide image on a 2× screen needs an 800 px wide file. It follows the browser's own choice from srcset, sizes and <picture>, and accounts for object-fit and transforms.

Contents

Installation

npx storybook add storybook-addon-image-resolution

This installs the package and adds it to addons in .storybook/main.ts. With CSF factories it also adds it to definePreview in .storybook/preview.ts.

Or by hand:

npm install -D storybook-addon-image-resolution

and add it to .storybook/main.ts:

const config = {
  addons: ['storybook-addon-image-resolution'],
};
export default config;

If your preview uses CSF factories (definePreview), add the addon there too, or nothing is inspected (the panel says "No report from the preview" after a few seconds). Storybook then takes the preview's settings only from there, not from main.ts. This also gives the types:

import imageResolution from 'storybook-addon-image-resolution';
export default definePreview({ addons: [imageResolution()] });

Requires Storybook 10 (10.3 or later) or Storybook 11. It works with every framework, since it only measures images in the preview iframe.

Usage

Inspection is off by default, and nothing runs while it is off. Turn it on with Inspect images in the toolbar popover (the button with a picture and an up/down arrow) or with Enable inspection in the Image resolution panel.

While it is on:

  • The panel lists every image with its status, its width and height as a percentage of the size it needs, and an explanation. Filters choose which statuses are shown (errors, warnings and unassessed images by default; images that are not rendered have a filter of their own, off by default); Show details gives the source, the painted and resource sizes and how they were measured; Highlight marks the image in the story.
  • Overlays outline the images in the story, with a short label (✕ 50%). The popover chooses all images, findings only, or none, and whether a label shows the worse side (✕ 50%) or width and height (✕ W 50% H 100%). On an image too small for its label, only the symbol is shown, and the full label when it is highlighted from the panel. Images that are not rendered get no outline unless highlighted. While a modal dialog is open, only the images in it (and in popovers opened over it) are outlined.
  • The panel's title shows how many errors, warnings and broken images there are.
Status Default
Warning below 90% or above 111.1%
Error below 75% or above 133.3%
Not applicable scalable images (SVG), which have no fixed resolution
Unassessed loading, broken, unavailable or without a source
Not rendered hidden, zero-size, or lazy and out of view

Not rendered means display: none, visibility: hidden, a closed <details>, no area, or a lazy image the browser has not loaded because it is out of view (an inactive carousel slide, a mobile-only image): there is nothing to judge until it shows.

The oversized thresholds are the reciprocals of the undersized ones (100 / 0.9 and 100 / 0.75); 75% is Lighthouse's limit for undersized images. A value exactly on a threshold passes; values are compared as shown, to one decimal, so 74.96% (shown as 75%) is on the 75% threshold. When the two axes disagree, the worse one decides. The thresholds can be changed in the popover (undersized 1–99%, oversized 101–400%; an error threshold is never milder than its warning); a field applies on Enter or when you leave it, and keeps the other threshold of its pair as shown, so the pair stays in order on stories with other defaults. Reset to defaults puts the thresholds, overlays and labels back to the story's defaults and leaves inspection on or off; Undo reset brings them back until the next change.

An image that is still loading after 5 seconds says so, so a stuck request is noticed.

Parameters

parameters: {
  imageResolution: {
    disable: true, // turn the addon off for this story
    defaults: {
      // same shape as the global
      enabled: true,
      overlays: 'findings',
      thresholds: { undersized: { warning: 80 } },
    },
  },
}

Defaults merge in Storybook's usual order: built-in defaults, project, component, story, then the user's own choices in the toolbar.

Do not set the imageResolution global through a story's globals: since Storybook 9 that locks the toolbar. Use parameters.imageResolution.defaults.

With CSF factories, the addon must also be in definePreview (see Installation); npx storybook add does this for you.

The types ImageResolutionInput, ImageResolutionParameters, ThresholdsInput and OverlayMode are also exported by name.

The global (public API)

Settings are stored in the imageResolution global, so they persist in the URL and can be shared. The global is sparse: it only holds what the user changed. Thresholds are plain numbers in percent.

imageResolution: {
  enabled: true, // missing means off
  // 'ratio' (worse side) or 'axes' (width and height); missing means 'ratio'
  labels: 'ratio',
  overlays: 'all', // 'all', 'findings' or 'off'; missing means 'all'
  thresholds: {
    undersized: { warning: 90, error: 75 },
    oversized: { warning: 111.1, error: 133.3 },
  },
}

Unknown or invalid fields are ignored with a console warning. An incompatible change to this shape comes with a new major version.

Inspecting in tests: inspectImages()

inspectImages() measures every <img> once the images have settled, for play functions and browser tests. It works whether interactive inspection is on or off, and cleans up after itself.

import { inspectImages } from 'storybook-addon-image-resolution';
import { expect } from 'storybook/test';

export const Gallery = {
  play: async ({ canvasElement }) => {
    const report = await inspectImages({ root: canvasElement });
    await expect(report.summary.error).toBe(0);
  },
};

Options: root (default: the document; an <img> as the root is inspected itself), thresholds (default: the built-in ones), timeout in milliseconds (default 5000) and an abort signal.

The report has a summary (counts of errors, warnings, passing, unassessed, not applicable and not rendered images), the context (DPR, viewport, thresholds) and an entry per image. Not rendered images are unassessed entries with the code hidden, zero-size or deferred, counted in notRendered instead of unassessed. An entry's kind is assessed, unassessed or not-applicable. An assessed entry has an assessment with a stable code (resolution-ok, resolution-undersized, resolution-oversized), its severity, both axes' classifications and an explanation; the others have a code saying why (such as loading or broken) and an explanation. An image counts as settled unless it is still loading; a lazy image outside the viewport is not forced to load. Which statuses fail your test is up to you: an unassessed or broken image is reported, never silently passed.

If images are still loading when the timeout runs out, the call rejects with an InspectionTimeoutError that carries the last report and the pending images, so an unfinished inspection never looks like a pass. If an inspection itself fails (an exception while measuring), the call rejects at once with that error.

Known limitations

  • Only <img>, including inside <picture>. CSS background images, pseudo-elements, canvas, video posters, SVG <image> elements, image buttons, iframes and shadow DOM are not inspected; the panel counts the ones it finds (except CSS backgrounds and closed shadow roots, which it cannot see).
  • The screen's real DPR only. There is no target-DPR setting; to check another density, change the browser's (device emulation, or deviceScaleFactor in Playwright).
  • Browsers keep a larger image they already have. Chromium reuses a larger srcset candidate already loaded in the document, and Storybook keeps one document across story switches, so an image can show as oversized after visiting another story; reload to see a fresh choice. WebKit keeps the larger candidate after the viewport shrinks.
  • Lazy images outside the viewport are reported as not loaded yet; browsers start lazy loads a little before an image scrolls into view.
  • Skew and 3D transforms give estimates (rotation and scaling are exact); pinch zoom and page zoom are not checked.
  • image-orientation: none on an EXIF-rotated photo: browsers do not report the file's stored size, so its axes are taken from the layout's proportions (an estimate).
  • Animations: an image animated with a transform (CSS animation, transition or the Web Animations API) is measured again when the animation ends, not during it. An endless animation keeps the result from when it started, and a Web Animations API animation started without any other change is not noticed. An animated width or height updates the results every frame while it runs.
  • Style changes made only through the CSS object model (insertRule, as CSS-in-JS libraries do in production builds) are not noticed until something else changes; <style> and <link> changes, <details>, popovers, and class, style, data-* and aria-* attributes of images and the elements that contain them are. Such an attribute on another element is noticed only when it resizes an image: one that only hides or shows an image through a sibling selector (.open + .panel img) is not, until something else changes.
  • Docs pages: inspection stays off there; it runs in the story canvas only.
  • A resolution match is not image quality: 100% says nothing about compression, format or transfer size.

Support

Please open an issue with a minimal reproduction (https://storybook.new).

License

MIT

Made by
  • timpii
    timpii
Work with
    Angular
    Ember
    HTML
    Marko
    Mithril
    Preact
    Rax
    React
    Riot
    Svelte
    Vue
    Web Components
Tags