🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Performance••By Komal Nakrani

Astro Image and Picture Components Explained

Astro image guide: use the Image and Picture components from astro:assets for optimized, responsive images, plus remote images, layouts, priority and getImage.

#Astro#Images#Image Component#Performance

The Astro image component, <Image /> from astro:assets, takes an imported image or an allowed remote URL and outputs an optimized <img>: converted to WebP, resized, with width and height set to prevent layout shift, and lazy-loaded by default. <Picture /> does the same but outputs a <picture> with several formats, such as AVIF with a WebP fallback. Both require alt.

This guide covers where to keep images, every prop that matters, responsive layouts, remote images, priority for the hero, images in content collections, and getImage() for cases the components do not cover.

Key Takeaways

  • Images in src/ are optimized; images in public/ are served as-is.
  • alt is required. Use alt="" for decorative images.
  • Remote images need image.domains or image.remotePatterns in the config, plus dimensions or inferSize.
  • Add priority to the one above-the-fold image that is your Largest Contentful Paint.
  • Set layout: 'constrained' to get srcset and sizes generated for you.

Where to put images in an Astro project

Astro treats images differently depending on where they live:

Location How you use it Optimized?
src/assets/ (or anywhere in src/) import hero from '../assets/hero.jpg' Yes
public/ src="/images/logo.png" string path No, served as-is
Remote URL src="https://..." Yes, if the domain is allowed
Content collection frontmatter image() schema helper Yes

Keep almost everything in src/assets/. Importing gives Astro the file’s real dimensions and format, which is what makes optimization and layout-shift prevention automatic. Reserve public/ for files that must keep an exact URL, such as favicon.ico or Open Graph images referenced by absolute path. The folder structure docs show where these directories sit.

The Image component

The basic usage is an import and two props:

---
// src/pages/index.astro
import { Image } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Image src={hero} alt="A desk with a laptop showing an Astro project" />

For a 2400 by 1600 JPEG, that renders something like:

<img src="/_astro/hero.Bx7c9a.webp" width="2400" height="1600"
  loading="lazy" decoding="async" alt="A desk with a laptop showing an Astro project">

Astro converted the file to WebP, fingerprinted the name for long-term caching, and set dimensions so the browser reserves space before the image loads. You will usually want it smaller than the original:

<Image src={hero} alt="..." width={1200} />

With only width set, Astro keeps the aspect ratio and calculates height for you.

Props you will actually use

  • src and alt: required. A missing alt fails the build with ImageMissingAlt; see the missing alt fix.
  • width, height: output size in pixels. Required for remote URLs and public/ paths unless you set inferSize.
  • format: 'webp' by default; also 'avif', 'png', 'jpeg' and others the service supports.
  • quality: a preset ('low', 'mid', 'high', 'max') or a number from 0 to 100.
  • densities: generate 1x and 2x versions for fixed-size images such as avatars, for example densities={[1.5, 2]}.
  • widths and sizes: generate a srcset of explicit widths for fluid images.
  • layout, fit, position: responsive behavior and cropping, covered below.
  • priority: load eagerly with high fetch priority.

Any other attribute, such as class or style, is passed straight to the <img>.

The Picture component

<Picture /> generates one <source> per format and an <img> fallback, so browsers pick the best format they support:

---
// src/components/Hero.astro
import { Picture } from 'astro:assets';
import hero from '../assets/hero.jpg';
---
<Picture
  src={hero}
  formats={['avif', 'webp']}
  alt="Team planning a website launch around a table"
  width={1600}
  pictureAttributes={{ class: 'hero-picture' }}
/>

AVIF files are typically smaller than WebP at similar quality but take longer to encode, so builds with many large images slow down. A sensible default is <Image /> (WebP only) for most images and <Picture /> with AVIF for the few large ones where bytes matter most, like the hero. The fallback <img> is PNG unless you set fallbackFormat, except for JPEG, GIF and SVG sources, which keep their original format.

For a side-by-side of the three options, read Image vs Picture vs img in Astro.

Responsive images with layout

Writing srcset and sizes by hand is tedious and easy to get wrong. The layout prop does it for you:

---
// src/components/PostCover.astro
import { Image } from 'astro:assets';
const { cover, alt } = Astro.props;
---
<Image src={cover} alt={alt} width={1200} height={630} layout="constrained" />

The three responsive layouts:

Layout Behavior Good for
constrained Scales down to fit its container, never above width Most content images, cards, covers
full-width Always fills the container width Hero banners, full-bleed sections
fixed Stays at width by height, with 1x and 2x versions Logos, avatars, icons

Each layout generates a srcset with a range of widths and a matching sizes attribute, and adds a few styles (including object-fit from the fit prop) so the image behaves as described. Set a site-wide default in the config so you do not repeat it on every image:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    layout: 'constrained',
    responsiveStyles: true,
  },
});

With responsiveStyles: true, Astro adds the small set of global styles the layouts need; turn it off if your CSS already handles image sizing. The responsive images tip has more examples, including art direction.

Remote images

Astro will not fetch and optimize images from arbitrary domains, to keep builds and server routes from being abused. Allow the domains you use:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  image: {
    domains: ['images.example-cms.com'],
    remotePatterns: [{ protocol: 'https', hostname: '**.cloudinary.com' }],
  },
});

A remote image also needs dimensions, because Astro cannot read them from an import:

---
// src/components/Avatar.astro
import { Image } from 'astro:assets';
const { url, name } = Astro.props;
---
<Image src={url} alt={name} width={96} height={96} />
<!-- or, when you do not know the size: -->
<Image src={url} alt={name} inferSize />

inferSize downloads the start of the file at build time to read its dimensions, which adds a network request per image. Prefer explicit sizes when your CMS provides them. If you see RemoteImageNotAllowed or MissingImageDimension, the remote image not allowed and missing image dimensions fixes cover them.

Priority for the LCP image

Every image is loading="lazy" and decoding="async" by default. That is right for most images, but wrong for the hero, which is often the page’s Largest Contentful Paint element. Lazy-loading it delays LCP.

Add priority to that one image:

<Image src={hero} alt="..." width={1600} layout="full-width" priority />

Astro then sets loading="eager", decoding="sync" and fetchpriority="high". Use it on one image per page, two at most. Marking everything as high priority means nothing is. The Core Web Vitals guide explains how to find your LCP element.

Images in content collections

For blog covers and other images referenced in frontmatter, use the image() helper in your schema. Astro resolves relative paths and validates that the file exists:

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
  schema: ({ image }) =>
    z.object({
      title: z.string(),
      cover: image(),
      coverAlt: z.string(),
    }),
});

export const collections = { blog };
---
// src/pages/blog/[id].astro (excerpt)
import { Image } from 'astro:assets';
const { post } = Astro.props;
---
<Image src={post.data.cover} alt={post.data.coverAlt} width={1200} />

The frontmatter value is a path relative to the Markdown file, such as cover: ./cover.jpg. Images used inline in Markdown with ![alt](./diagram.png) are optimized automatically too. The Content Collections guide covers schemas in full.

getImage() for everything else

Sometimes you need an optimized image URL without an <img> element: a CSS background, an Open Graph tag, or an image passed to a framework component. getImage() returns the generated src and attributes:

---
// src/components/HeroBackground.astro
import { getImage } from 'astro:assets';
import bg from '../assets/texture.jpg';

const optimized = await getImage({ src: bg, width: 1920, format: 'webp' });
---
<section class="hero" style={`background-image: url(${optimized.src})`}>
  <slot />
</section>

getImage() runs on the server only. Calling it from client-side code throws GetImageNotUsedOnServer, covered in the getImage server-only fix.

Image service and build performance

Astro uses Sharp to process images by default. It is fast, but a site with hundreds of large photos still spends real time on image work during builds. Three habits keep builds quick:

  1. Resize source images before committing them. A 6000-pixel camera original is rarely needed for a 1200-pixel layout.
  2. Use AVIF selectively, since it is the slowest format to encode.
  3. Cache the node_modules/.astro directory in CI so unchanged images are not reprocessed; the CI build cache tip shows how.

If your host optimizes images itself, or you cannot install Sharp, switch to passthroughImageService() from astro/config in image.service. Images then keep their dimensions and layout-shift protection but are not converted or resized.

The official images guide and the astro:assets API reference document every prop. Image-heavy sites such as portfolios get the most from all of this, and the Astro portfolio themes are a good place to see responsive galleries built on astro:assets.

FAQ

What is the difference between Image and Picture in Astro?

<Image /> outputs a single <img> in one format, WebP by default. <Picture /> outputs a <picture> element with a <source> for each format you list, such as AVIF and WebP, plus an <img> fallback.

Why are images in the public folder not optimized?

Astro copies public/ to the build unchanged, even when you pass a public/ path to <Image />. To optimize an image, move it into src/ and import it.

How do I make Astro images responsive?

Set layout="constrained" or layout="full-width" on the component, or image.layout in astro.config.mjs as a default. Astro then generates srcset and sizes automatically.

How do I use remote images with the Astro Image component?

Add the domain to image.domains or a pattern to image.remotePatterns in your config, then pass the URL as src with width and height, or with inferSize if you do not know the dimensions.

Should every Astro image use priority?

No. Use priority only on the main above-the-fold image, usually the hero. Every other image should stay lazy-loaded, which is the default.