Skip to content

@ogygia/image

Markdown images

With @ogygia/content, ![alt](./photo.jpg) in a post renders through <Img>, and a frontmatter line like cover: ./cover.jpg becomes an image descriptor your schema can check, while a JSON collection looks its images up with a glob.

On this page

A post is mostly words, but most posts have a few pictures and a cover. With both plugins listed, the pictures in a markdown file render through <Img> with no import and no component in the post, and a cover named in the frontmatter becomes a descriptor you can render anywhere.

---
title: A walk to the harbor
cover: ./cover.jpg
---

![The harbor in the evening](./harbor.jpg "Seen from the pier")

Setup

List content({ markdown }) and image() together. The image plugin offers the content plugin a markdown step, and the content plugin runs it on every .md and .svx file. There’s nothing else to set up. Publish content covers the content plugin’s own setup (its svelte.config.js lines and types).

Declare a prose preset for body images; without one, each image is as wide as itself.

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

export default defineConfig({
  plugins: [
    ogygia(),
    content({ markdown: {} }),
    image({
      presets: {
        cover: {
          layout: 'fullWidth',
          aspect: '16/9',
          priority: true
        },
        prose: { width: 720 }
      }
    }),
    sveltekit()
  ]
});

Body images

A local image in markdown, ![alt](./photo.jpg), renders through <Img>. Its text becomes alt, and its title, if it has one, becomes the <img>’s title.

  • Paths are relative to the post, like an import. ../other-post/diagram.png reaches into another folder. A name with spaces or accents works written as it is (![](<./my photo.jpg>)) or URL-encoded (./my%20photo.jpg). An escape that doesn’t decode to UTF-8 fails with image_path_malformed.
  • A missing file fails the build with image_not_found, naming the post and the path. The file must sit under src/ like any image (Keep images under src/).
  • The prose preset is how every body image is shown, when you declare one. Without it, image({ markdown: { width } }) gives the prose column’s width in CSS pixels. Leave both out and each image is as wide as itself.
  • Remote images on a listed host (image({ remote: { hosts } })) render through <Img> like local ones (Images from other hosts). Any other remote image, and a site-absolute one (/images/x.png, served from static/), stays a plain <img>.
  • An HTML <img> that names a local file fails the build with image_markdown_html: it’s copied as text, so its relative path would point at nothing once served. Write it as ![alt](./photo.jpg).

The extensions read are .png, .jpg, .jpeg, .webp, .avif, .gif, .svg, .tif and .tiff.

Swapped image elements

With content({ markdown: { overrides } }) and a site’s components.img (Swap how markdown elements render), the image step runs first. A local image or one on a listed host renders through <Img>, so your img component never sees it. Only the images that stay plain <img> (unlisted hosts, site-absolute paths) reach your component.

Markdown from a string

import.meta.og.md(text) renders markdown from a string, which has no file to resolve a path against. A local image there fails the build with image_markdown_no_file. Use a site-absolute or remote URL there, put the image in the component with <Img>, or move the markdown into a .md file.

Static posts

A .md post with a local image, or one on a listed host, renders a component, so it’s compiled as a Svelte component, not kept as static HTML. With content({ markdown: { region: true } }), such a post leaves the static path; a post whose images all stay plain <img> tags still takes it.

---
title: A walk to the harbor
---

![The harbor in the evening](./harbor.jpg "Seen from the pier")

![](<./boats at dawn.jpg>)

![A map of the walk](../shared/map.png)

![Our logo](/logo.png)

Animated images

An animated GIF or WebP in a post usually looks best narrower than a photo. image({ markdown: { animated } }) names the preset a moving image takes instead of prose. Its width and sizes reach the srcset, so the browser downloads the narrow file, and on a prerendered page the build makes only that preset’s files. Still images keep the prose preset.

The name must be a preset you declare, or the build fails with image_option_invalid. In a component, read of.animated and pick the preset yourself (Less motion).

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

export default defineConfig({
  plugins: [
    ogygia(),
    content({ markdown: {} }),
    image({
      presets: {
        prose: { width: 720 },
      motion: { width: 400, sizes: '33vw' }
      },
    markdown: { animated: 'motion' }
    }),
    sveltekit()
  ]
});

Opting out

image({ markdown: false }) leaves markdown alone: images stay plain <img> tags, frontmatter paths stay strings, and every post can take the static path again. Components still use <Img> as usual.

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

export default defineConfig({
  plugins: [
    ogygia(),
    content({ markdown: {} }),
    image({ markdown: false }),
    sveltekit()
  ]
});

Frontmatter images

A frontmatter value that starts with ./ or ../ and ends in an image extension becomes a descriptor at build, wherever it sits: a nested object or a list works too. A missing file fails the build with image_not_found. A URL on a host image({ remote: { hosts } }) lists (cover: https://images.example.com/c.jpg) becomes a descriptor too, fetched at build.

A listed host’s URL doesn’t need an image extension: any http(s) URL on that host is fetched as an image, so source: https://images.example.com/post.pdf fails the build with image_remote_failed (“not an image”). Keep other links to that host out of frontmatter, or on another host (#2290).

Other strings stay strings: images/share.png, diagram.png and a URL on an unlisted host are left alone.

Check it in the schema

In the collection’s schema, accept the descriptor with isImage, a check that a value is a descriptor: v.custom<ImageDescriptor>(isImage) with valibot, z.custom<ImageDescriptor>(isImage) with zod. A value that’s still a string (a path without ./ or ../) fails the check, so a typo shows up as a schema error.

Define the collection in a .server.ts file, like every collection (Define the collection in a server module), so its posts never reach a browser bundle.

Render the cover

Load the post in +page.server.ts. A descriptor is plain data, and an awaited body is HTML the server already rendered, so both cross to the page. A body crossing from a load needs ogygia’s transport hook.

The images in the body survive that: they’re the server’s <Img> markup, files and all.

---
title: A walk to the harbor
cover: ./cover.jpg
gallery:
  - ./one.jpg
  - ./two.jpg
author:
  name: Ana
  photo: ../../authors/ana.jpg
---
import { content } from '@ogygia/content';
import { isImage, type ImageDescriptor } from '@ogygia/image';
import * as v from 'valibot';

export const blog = content({
  loader: import.meta.og.loader.markdown(
    '../content/blog/*/+post.md',
    {
      id: (key) => key.split('/').at(-2) ?? key
    }
  ),
  schema: v.object({
    title: v.string(),
    cover: v.custom<ImageDescriptor>(isImage)
  })
});
import { error } from '@sveltejs/kit';
import { blog } from '$lib/blog.server';

export async function load({ params }) {
  const post = await blog.get(params.slug);
  if (!post) error(404, 'Not found');
  return { ...post.data, body: await post.body };
}
<script lang="ts">
  import { Region } from 'ogygia';
  import { Img } from '@ogygia/image';

  let { data } = $props();
</script>

<Img of={data.cover} preset="cover" alt={data.title} />
<h1>{data.title}</h1>
{#if data.body}<Region of={data.body} />{/if}

JSON collections

Only markdown frontmatter turns a path into a descriptor. A JSON collection (import.meta.og.loader.json, a CMS) keeps its strings as they are, so "cover": "acme.png" stays a string. Read the folder of images once with a glob beside the collection, and look each one up by its name.

The glob’s keys are the paths as the pattern writes them, relative to the file. Every file it matches is a source, and published like any image under src/, whether an entry names it or not. The schema field stays v.string().

Look the cover up in the server load. The descriptor is plain data, so it crosses to the page.

A path relative to the entry’s own folder

When each entry sits in its own folder with its image (src/content/talks/<kind>/<talk>/+detail.json next to image.png, written "cover": "./image.png"), give each entry its folder as its id, and join the path to it.

The entry meetup/00-intro names "./image.png", which is the glob’s key ../content/talks/meetup/00-intro/image.png. The load maps each entry as above, with cover: beside(r.id, r.data.cover). A ../ path that leaves the entry folders needs a wider glob (../content/talks/**/*.{png,jpg}).

import { content } from '@ogygia/content';
import type { ImageDescriptor } from '@ogygia/image';
import * as v from 'valibot';

export const work = content({
  loader: import.meta.og.loader.json('../content/work'),
  schema: v.object({ title: v.string(), cover: v.string() })
});

const covers = import.meta.og.image.glob(
  '../content/work/*.{png,jpg}'
);

/** The cover a work entry names (`"cover": "acme.png"`), from src/content/work/. */
export function cover(name: string): ImageDescriptor {
  const found = covers[`../content/work/${name}`];
  if (!found)
    throw new Error(
      `src/content/work/ has no cover named ${name}`
    );
  return found;
}
import { cover, work } from '$lib/work.server';

export async function load() {
  const refs = await work.refs();
  return {
    items: refs.map((r) => ({
      id: r.id,
      ...r.data,
      cover: cover(r.data.cover)
    }))
  };
}
<script lang="ts">
  import { Img } from '@ogygia/image';

  let { data } = $props();
</script>

{#each data.items as item (item.id)}
  <Img of={item.cover} preset="thumb" alt={item.title} />
{/each}
import { content } from '@ogygia/content';
import type { ImageDescriptor } from '@ogygia/image';
import * as v from 'valibot';

export const talks = content({
  loader: import.meta.og.loader.json(
    '../content/talks/*/*/+detail.json',
    {
      id: (key) => key.split('/').slice(-3, -1).join('/')
    }
  ),
  schema: v.object({ title: v.string(), cover: v.string() })
});

const images = import.meta.og.image.glob(
  '../content/talks/*/*/*.{png,jpg}'
);

/** The image the entry `id` names by a path relative to its own folder (`./image.png`, `../x.png`). */
export function beside(
  id: string,
  rel: string
): ImageDescriptor {
  const key = `..${decodeURIComponent(new URL(rel, `file:///content/talks/${id}/`).pathname)}`;
  const found = images[key];
  if (!found)
    throw new Error(
      `src/content/talks/${id}/ has no image ${rel}`
    );
  return found;
}