Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Styling and Assets

Images in Astro: Image, Picture and getImage

Optimise images in Astro with the Image and Picture components, remote image rules, responsive widths, formats, getImage and layout shift prevention.

Images are usually the heaviest part of a page. Astro includes an image pipeline in the astro:assets module that resizes, converts and fingerprints images at build time, and writes width and height attributes so the browser reserves space before the file arrives. This lesson covers where to put images, the <Image /> and <Picture /> components, remote images, and the getImage() function.

Where images live

There are two homes, and the difference matters:

Location Processed? Reference with
src/assets/ (any folder under src) Yes: resized, converted, hashed import
public/ No: copied as is an absolute URL like /logo.png

Put photos and illustrations in src/; use public/ only for files that need a stable URL (favicon.ico, robots.txt, files linked from outside).

The Image component

ASTRO
---
import { Image } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Image src={hero} alt="A mountain lake at sunrise" />

Importing the file gives Astro its real dimensions. The output is an optimised <img> with src, width, height, loading="lazy" and decoding="async" already set. Because width and height are present, the browser knows the aspect ratio from the first byte of HTML, which prevents layout shift.

Useful props:

ASTRO
<Image
  src={hero}
  alt="A mountain lake at sunrise"
  width={800}
  quality="mid"
  format="webp"
  loading="eager"
/>
  • width / height: output size. Give only one and the other follows the ratio.
  • format: webp by default; avif, png, jpeg are available.
  • quality: a number from 0 to 100 or low, mid, high, max.
  • loading="eager" and fetchpriority="high" for the main image above the fold (your LCP element). Everything else should stay lazy.

alt is required. Leaving it out is a build error, and on purpose: write a real description, or alt="" for purely decorative images.

Responsive images

Phones and desktops want different file sizes. Give the component several widths and a sizes hint:

ASTRO
<Image
  src={hero}
  alt="A mountain lake at sunrise"
  widths={[400, 800, 1200]}
  sizes="(max-width: 800px) 100vw, 800px"
/>

Astro generates three files and a srcset. Newer Astro versions also offer a layout option (constrained, full-width, fixed) that produces the srcset and sizes for you, set globally under image in the config or per component.

The Picture component

<Picture /> outputs a <picture> element with one <source> per format, so modern browsers get AVIF or WebP and old ones fall back:

ASTRO
---
import { Picture } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Picture
  src={hero}
  formats={['avif', 'webp']}
  alt="A mountain lake at sunrise"
/>

Use Picture for hero images where bytes matter most; use Image for everyday content.

Remote images

A remote URL has no known size at build time, so you must either pass width and height, or use inferSize:

ASTRO
<Image
  src="https://cdn.example.com/team.jpg"
  alt="The team"
  width={600}
  height={400}
/>
<Image src="https://cdn.example.com/team.jpg" alt="The team" inferSize />

Astro only optimises remote images from hosts you authorise:

JavaScript
// astro.config.mjs
export default defineConfig({
  image: {
    domains: ['cdn.example.com'],
    remotePatterns: [{ protocol: 'https', hostname: '**.example.org' }],
  },
});

Anything not listed is still rendered, but untouched.

Images in Markdown and content collections

In Markdown, a relative path such as ![Lake](./lake.jpg) is optimised automatically. In a content collection schema, use the image() helper so front matter paths become real imports:

TypeScript
import { defineCollection, z } from 'astro:content';

const posts = defineCollection({
  schema: ({ image }) =>
    z.object({
      title: z.string(),
      cover: image(),
      coverAlt: z.string(),
    }),
});

Then <Image src={post.data.cover} alt={post.data.coverAlt} /> just works and a missing file fails the build.

getImage: when you need a URL

<Image /> outputs a tag. For CSS backgrounds, Open Graph tags, or your own markup, call getImage():

ASTRO
---
import { getImage } from 'astro:assets';
import hero from '../assets/hero.jpg';

const og = await getImage({ src: hero, width: 1200, height: 630, format: 'jpg' });
---
<meta property="og:image" content={new URL(og.src, Astro.site)} />

The image service

By default Astro uses Sharp to do the work at build time. In server mode, the same service backs a /_image endpoint that processes images on demand. Platforms that cannot run Sharp (some edge runtimes) provide their own service, or you can disable optimisation with passthroughImageService().

Try it: srcset math

This stand-in shows what the build computes for a responsive image: widths capped at the source size, heights from the aspect ratio, and the srcset string.

JS Build a srcset

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that 2400 is dropped: Astro never upscales beyond the source.

Try it: layout shift budget

Why do width and height matter? This stand-in compares the page jump with and without reserved space.

JS Reserved space vs. layout shift

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which images are optimised by Astro automatically?

    Files in public/ are copied untouched. Imported assets in src/ go through the image service.
  2. 2. Why does a remote image need width and height (or inferSize)?

    A local import exposes its dimensions. For a URL, Astro needs you to supply them or let it fetch the image to infer them.
  3. 3. When would you choose <Picture /> over <Image />?

    Picture emits a picture element with one source per format, so each browser picks the best one it supports.
  4. 4. Which call gives you an optimised URL for a meta tag instead of an img element?

    getImage() from astro:assets returns the generated src (and attributes) so you can use it anywhere.

Summary

  • Put processed images in src/, static-as-is files in public/.
  • <Image /> writes dimensions, lazy loading and modern formats; <Picture /> adds multiple formats.
  • Use widths/sizes (or layout) for responsive images; keep the main hero eager.
  • Authorise remote hosts under image.domains or remotePatterns.
  • getImage() returns optimised URLs for any use.

Next: Fonts, Icons and Static Assets