Skip to content

@ogygia/image

Img component

Read an image file at build with import.meta.og.image(), then render it with <Img>. You say how it sits on the page, by preset or by layout, and <Img> works out the files, the srcset, the sizes, the box and the loading hints.

On this page

Showing an image takes two steps. import.meta.og.image(path) reads the file at build and gives you its descriptor: the source, its size and its placeholder, as plain data (every field). <Img> takes the descriptor and renders it, the way a preset or its own props say.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const hero = import.meta.og.image('../lib/images/hero.jpg');
  const avatar = import.meta.og.image(
    '../lib/images/avatar.jpg'
  );
</script>

<Img of={hero} preset="cover" alt="The harbor at dusk" />
<Img of={avatar} layout="fixed" width={48} height={48} alt="" />

Image files

import.meta.og.image(path, options?) is a macro. The build rewrites each call into an import of the file and turns that into the descriptor, so it costs nothing at run time.

  • The path is relative to the file that calls it, like a relative import. Aliases such as $lib/… aren’t resolved: write ../lib/images/hero.jpg. A path that names no file fails the build with image_not_found.
  • The arguments are written out in place: a string path and, if you pass options, an object of plain values. The build reads them before any code runs, so a variable, a function call or a ${…} in the path fails with image_macro_not_literal. More than two arguments, or none, fails with image_macro_arity.
  • Call it in a <script> or a module: a .ts or .js file, a component’s script, or a markdown page’s (.svx, .md). A call in a template expression fails the build with macro_in_markup.
  • The options belong to the source, whatever page shows it: quality, placeholder, ops (pixel operations), warm, dark and art. Image options lists them. An unknown key fails with image_option_unknown.

It reads PNG, JPEG, WebP, AVIF, GIF, TIFF and SVG. A file it can’t decode fails the build with image_decode_failed, and one past 268,402,689 pixels a frame (16383 × 16383), or an animation past 4,294,967,296 pixels over all its frames, with image_too_large.

Keep images under src/

The file must sit under src/, outside src/lib/server/ and outside test files (*.test.*, *.spec.*, __tests__/). Anything else fails with image_outside_src. The image endpoint reads the original with Kit’s read(), which only reads assets the server bundle carries, so the plugin makes every image under src/ one of the server’s assets.

That means every raster image under src/ is published, used or not: each PNG, JPEG, WebP, AVIF, GIF and TIFF gets a public hashed URL beside the app’s other assets, and ships with the server (a serverless function counts it toward its size). Keep drafts and originals you don’t want public out of src/, or under src/lib/server/.

export const team = import.meta.og.image('./images/team.jpg', {
  quality: 70,
  ops: { grayscale: true }
});
src/
  lib/
    images/hero.jpg        published, usable
    server/raw/hero.psd    never published
  routes/blog/cover.png    published, usable
static/logo.png            not usable by the macro

Globs

import.meta.og.image.glob(pattern, options?) reads every image a glob matches and returns their descriptors, keyed by path as the pattern writes it. The options apply to every match. A pattern that matches nothing fails the build with image_glob_empty, since an empty gallery is almost always a wrong pattern.

A glob is local only: a URL there fails with image_option_invalid. It also takes no dark or art, since each match would need its own twin file.

The macro needs literal paths, so to pick an image at run time, read every candidate with a glob and choose among them.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const gallery = import.meta.og.image.glob('./photos/*.jpg');
</script>

{#each Object.entries(gallery) as [path, photo] (path)}
  <Img of={photo} preset="thumb" alt="" />
{/each}

<Img>

<Img> renders one descriptor. Its props say how the image sits on the page; a preset names a set of them, and the props you pass say over the preset’s.

PropDefaultWhat it does
ofrequiredThe descriptor: from the macro, a glob, a markdown or frontmatter image, remoteImage() or a share card.
altrequiredWhat the image shows. Use "" for a decorative image.
presetnoneA preset from image({ presets }).
layout'constrained'How the image sits on the page: 'constrained', 'fullWidth' or 'fixed' (Pick a layout).
widthnoneDisplay width, in CSS pixels. Doesn’t set the size with fullWidth.
heightnoneDisplay height, in CSS pixels. With width, the files are cropped to that box.
aspectnoneThe box’s shape, 16 / 9 or '16/9'. The files are cropped to it.
position'center'Where a crop keeps (Crop to a shape).
sizesderivedReplaces the sizes the layout works out, for a layout the three can’t say.
priorityfalseThe page’s main image: loads eagerly, at high priority, preloaded from the head.
placeholdertruePaint the blur placeholder until the image arrives.
morphfalseGlide into the same source on the next page in a client-side navigation.
artpreset’sOther crops or files at other media conditions (Art direction).

Besides these, class, id, style, title, crossorigin, referrerpolicy and draggable pass through to the <img>. Other attributes don’t, data-* and aria-* included: spreading attributes onto an <img> makes Svelte write inline onload and onerror handlers, which a strict CSP blocks. Wrap the image in an element of your own when you need more.

<script lang="ts">
  import { Img, type ImageDescriptor } from '@ogygia/image';

  let { of, name }: { of: ImageDescriptor; name: string } =
    $props();
</script>

<Img
  {of}
  preset="avatar"
  alt={name}
  class="avatar"
  title={name}
/>

Presets

A preset is a name for how your site shows an image. Declare it once in image({ presets }) and pick it with <Img preset="…">. It takes the same keys as the props above (layout, width, height, aspect, position, sizes, priority, placeholder, morph, art) plus two that only a preset or getImage() can set: quality (1 to 100) and formats (best first). A preset name starts with a letter and holds letters, digits, - and _.

Each prop you pass says over the preset’s value, so the same preset can be tuned on one page. An unknown preset name fails the render with image_preset_unknown, and a bad value in a preset fails the build with image_option_invalid.

Two names mean something to the plugin: prose is the preset every markdown body image uses when it’s declared, and markdown.animated can name the one a moving markdown image takes.

import { sveltekit } from '@sveltejs/kit/vite';
import { ogygia } from 'ogygia/vite';
import { image } from '@ogygia/image/vite';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    ogygia(),
    image({
      presets: {
        cover: {
          layout: 'fullWidth',
          aspect: '16/9',
          priority: true
        },
        thumb: { width: 400, aspect: '1/1' },
        avatar: { layout: 'fixed', width: 48, height: 48 },
        share: { width: 1200, height: 630, formats: ['jpeg'] },
        prose: { width: 720 }
      }
    }),
    sveltekit()
  ]
});
<script lang="ts">
  import { Img } from '@ogygia/image';

  const cover = import.meta.og.image('./cover.jpg');
</script>

<Img of={cover} preset="thumb" alt="" />             <!-- a square file, 400 wide -->
<Img of={cover} preset="cover" alt="" />             <!-- a 16:9 hero, preloaded -->
<Img of={cover} preset="thumb" width={200} alt="" /> <!-- the thumb, smaller -->

Layouts

The layout says how the image sits in its container. The files, the srcset and the sizes follow from it:

  • constrained (the default): as wide as width, or as the image itself when you leave width out. It shrinks with its container and never grows past that width. sizes is (min-width: <width>px) <width>px, 100vw. The files are the width and twice it, plus the steps of the width ladder below twice the width.
  • fullWidth: the container’s full width on every screen, for heroes and banners. sizes is 100vw, and the files are the whole ladder up to the image’s own width. width doesn’t set the size: the width attribute is the image’s own width (or its crop’s), and CSS stretches it. To crop a fullWidth image, give the shape as aspect (aspect="1200/630"), not a width and a height: with both, the files get the crop’s shape but the box keeps the asked height, so the page reserves the wrong space and the file is cropped twice (#2290). getImage() returns the same wrong height.
  • fixed: exactly width × height CSS pixels, for avatars and icons. The files are exactly 1× and 2× the width (48 and 96 pixels for a 48-pixel avatar), as a density srcset (1x, 2x), with no sizes.

The ladder is image({ breakpoints }), [320, 480, 640, 960, 1280, 1600, 2048] by default. A step within a tenth of a width the layout names is left out: an image shown 900 wide gets no 960-pixel file beside its 900 one. No file is ever wider than the source can cover, so a small image never gets an upscaled file.

The layout’s own CSS is a zero-specificity rule on data-og-img: constrained gets max-width: 100%; height: auto, fullWidth gets width: 100%; height: auto, and fixed gets nothing. Any class of yours wins over it.

The demo shows one photo under each layout: constrained at width={480}, fullWidth, and fixed at 160 × 90. The frame is the page’s viewport, so drag its width and each image says how wide its box is and which file the browser picked from its srcset. A fixed image picks by your screen’s density alone. The browser fetches a wider file as the frame grows, and it keeps a wider file it already has when the frame shrinks.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const team = import.meta.og.image('./team.jpg');
  const badge = import.meta.og.image('./badge.png');
</script>

<!-- 640 and 1280 wide, plus 320, 480 and 960 for narrower screens -->
<Img of={team} width={640} alt="The team" />

<!-- the container's width, the whole ladder -->
<Img of={team} layout="fullWidth" alt="The team" />

<!-- exactly 32 × 32, at 1x and 2x -->
<Img of={badge} layout="fixed" width={32} height={32} alt="" />
/demo/image-layouts · drag the width
full

Cropping

Give an aspect, or both a width and a height, and every file is cut to that shape. The crop happens when the file is made, so a square thumbnail downloads a square file. The <img> keeps the box with object-fit: cover and aspect-ratio, and the files are never wider than the source can cover at that shape.

position says which part of the image a crop keeps: 'center' (the default; 'centre' works too), 'top', 'bottom', 'left', 'right', or one of sharp’s smart crops, 'attention' (the most striking part) or 'entropy' (the busiest). Cloudflare can’t make an 'entropy' crop and Vercel can’t crop at all; What each encoder can make has the table.

A file named for a crop carries its position, so top and attention crops of one source are separate files. An SVG is never cropped: it scales on its own.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const portrait = import.meta.og.image('./portrait.jpg');
</script>

<Img
  of={portrait}
  width={300}
 aspect="4/5"
  position="attention"
 alt="Our founder"
/>
<Img
  of={portrait}
 width={120}
  height={120}
  position="top"
 alt=""
/>

Priority

Give priority to the one image that is the page’s largest paint, usually the hero. It sets loading="eager", decoding="sync" and fetchpriority="high", and adds a <link rel="preload" as="image"> to the head for the best format, with the same imagesrcset and imagesizes, so the browser starts the download before it reads the body.

Every other image gets loading="lazy" and decoding="async", so it downloads as the visitor scrolls near and decodes off the main thread. The profiler’s page insights flag a largest paint that’s still lazy (the lcp-lazy insight).

An image with twins writes one preload per candidate set, each with the media it’s shown at, so each visitor preloads only the file the <picture> will pick (Art direction). An <Img> that renders in the browser adds no preload when the server already wrote one.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const hero = import.meta.og.image('../lib/images/hero.jpg');
</script>

<Img
  of={hero}
  layout="fullWidth"
  aspect="16/9"
 priority
 alt="The harbor at dusk"
/>

Morph transitions

With morph on a thumbnail and on the post’s hero of the same source, a client-side navigation between the two pages gives both the same view transition name (og-img-<source id>), so the thumbnail glides into place. It needs the SPA router with view transitions on, which is the default.

Use it on at most one image per source on a page: a view transition name that appears twice cancels the page’s transition. A source is its bytes, not its file name or its options. Two imports of the same bytes are one source and share the name, even with different ops.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const cover = import.meta.og.image('./harbor/cover.jpg');
</script>

<a href="/blog/harbor">
  <Img of={cover} preset="thumb" morph alt="" />
</a>
<script lang="ts">
  import { Img } from '@ogygia/image';

  const cover = import.meta.og.image('../harbor/cover.jpg');
</script>

<Img
  of={cover}
  preset="cover"
 morph
 alt="The harbor at dusk"
/>

Placeholders

Each descriptor carries a placeholder: the image shrunk to 16 pixels wide, as a WebP data: URL of a few hundred bytes. <Img> paints it as the <img>’s background, stretched to cover the box, so the visitor sees the image’s colors at once and the real file paints over it.

Some images get none:

  • A transparent image, since the blur would show through it. Any pixel that isn’t fully opaque counts.
  • An SVG, which is served as it is.
  • A remoteImage() and a share card, whose pixels the build never reads.

To turn it off, pass placeholder: false to the macro (no placeholder is made for that source), set it in a preset, or pass placeholder={false} to <Img>. image({ placeholder: false }) turns it off for every source that doesn’t set its own.

In the demo, the replay button hides the loaded photo for a moment and fades it back in over its placeholder, the way a slow connection shows it. The placeholder is the descriptor’s own, a few hundred bytes written into the HTML.

<script lang="ts">
  import { Img } from '@ogygia/image';

  const logo = import.meta.og.image('../lib/images/logo.jpg', { placeholder: false });
  const hero = import.meta.og.image('../lib/images/hero.jpg');
</script>

<Img of={logo} layout="fixed" width={120} alt="Harbor Co." />
<Img of={hero} preset="cover" placeholder={false} alt="" />
Blur placeholder
An island with a palm, at sea

placeholder 66 B, inline in the HTML · file 2400 × 1350 source

HTML output

<Img> renders a <picture>: one <source> per format but the last, best first, then the <img> with the last format as its srcset and fallback src. With one format and no twins it renders the <img> alone. The <img>’s width and height are the box, so the page reserves its space before any file arrives.

It writes no script and no inline event handler, so a strict script-src has nothing to block. The placeholder, a crop’s object-fit and aspect-ratio, and morph’s view transition name go in the <img>’s style attribute, and the placeholder is a data: image. A CSP that limits those needs img-src data: and style-src-attr 'unsafe-inline', or no placeholder, no crop and no morph.

Here’s a 1600 × 900 photo with layout="fullWidth" and aspect="16/9", on a page rendered on a live server:

Sizes that stop the render

Sizes are whole pixels. A width or height with a fraction (width={1000 / 3}) is rounded. The render stops with image_prop_invalid when a value would name a file no server makes:

  • a size of 0 or less, or one that isn’t a number;
  • an aspect that doesn’t read as a ratio;
  • a box taller than the source can fill (aspect="1/100000" on a 900-pixel-tall image);
  • a file past 99999 pixels a side;
  • a position that isn’t one of the crop positions;
  • a quality passed to getImage() that isn’t a whole number from 1 to 100 (72.5 is refused, not rounded) (a preset’s fails the build instead);
  • an art twin whose media isn’t a condition in parentheses;
  • a descriptor whose id or placeholder the build didn’t make (one stored somewhere and changed by hand).

getImage() follows the same rules.

<picture>
  <source
    type="image/avif"
    srcset="
      /__ogygia__/i/…/Xk2j…-320x180/_app/immutable/assets/hero.Bx1.jpg.avif   320w,
      …,
      /__ogygia__/i/…/Xk2j…-1600x900/_app/immutable/assets/hero.Bx1.jpg.avif 1600w
    "
    sizes="100vw"
  />
  <img
    src="/__ogygia__/i/…/Xk2j…-1600x900/_app/immutable/assets/hero.Bx1.jpg.webp"
    srcset="…webp 320w, …, …webp 1600w"
    sizes="100vw"
    width="1600"
    height="900"
    alt="The harbor at dusk"
    loading="lazy"
    decoding="async"
    data-og-img="fullWidth"
    style="background-image:url(data:image/webp;base64,…);background-size:cover;background-repeat:no-repeat;object-fit:cover;aspect-ratio:1600/900"
  />
</picture>

getImage()

getImage(descriptor, options?) returns what <Img> would render, as data: the same files and the same URLs (signed on a live server, the build’s files on a prerendered page, an encoder’s links where it names them). Use it for a CSS background, an og:image, or a <picture> of your own. Like <Img>, it runs on the server.

It takes a preset, layout, width, height, aspect, position, sizes and art, plus quality and formats. It returns a Laid:

FieldWhat it is
srcThe <img>’s fallback file: the last format, at least as wide as the box.
srcsetThe <img>’s own srcset, in the last format.
sizesThe sizes the layout works out, or yours.
widthThe box’s width, for the width attribute.
heightThe box’s height.
sourcesThe <source> rows (LaidSource: media, type, srcset, sizes, width, height), twins first.
covertrue when the box has its own shape and the files are cut to it.
preloadsThe preloads a priority image writes (LaidPreload: href, type, srcset, sizes, media).
darkWith image({ theme }), the dark file laid out as its own picture.

The types Laid, LaidSource, LaidPreload, GetImageOptions and LayoutRequest are exported from @ogygia/image.

<script lang="ts">
  import { getImage } from '@ogygia/image';

  const photo = import.meta.og.image('../lib/images/photo.jpg');
  const laid = getImage(photo, {
    layout: 'fullWidth',
    aspect: '21/9',
    formats: ['jpeg']
  });
</script>

<section
  class="banner"
  style="background-image: url({laid.src})"
>
  <h1>Welcome</h1>
</section>

Images in islands

An <Img> inside an island renders on the server first, and keeps the server’s file URLs when it hydrates: the browser has no key to sign with, so it reads them back from the page.

A render that only happens in the browser (an {#if} that turns true after a click, say) can’t sign. It names a warmed preset’s static files when the build made them, or the encoder’s own links (cloudflare(), vercel()), and otherwise shows the original file at full size. A remoteImage() rendered only in the browser shows its original URL. Render images on the server, or warm the preset an island shows.

getImage() called in the browser follows the same rule. A share card’s maker can’t run there at all: it fails with image_no_server, so make the card in a server load and pass its descriptor down (Social cards).