Essential CSS
JavaScript Roadmap
Learn JavaScript
Mastering Web Typography
Practical Astro
Understanding Async JS
Unorthodox Tailwind
API Masterclass
Build and Deploy
The Beginner Freelancer
Real World Node
Profile Billing Logout
Practical Astro
Lesson Plan
  1. Content Systems
    1. Introduction
    2. An import alias
    3. Using Markdown
    4. Markdown extended
    5. Markdown component
    6. Markdown component in frameworks
    7. Content collections made easy
    8. Basic blogs
    9. Blogs made easy
    10. Prev/Next navigation
    11. Pagination made easy
    12. Better tag pages
    13. Paginated tag pages
    14. Markdown layouts
    15. Partials
    16. JS over JSON Data
    17. Dynamic 404 pages
    18. Putting everything together
    19. Other useful systems
  2. Image Systems
    1. Introduction
    2. Images are complicated because of this
    3. Astro's Image component
    4. Astro's Picture component
    5. Improvements over Astro's Image and Picture Components
    6. Images in Markdown and MDX
    7. Images in framework components
    8. Background images
    9. Art Direction with Astro
    10. Videos without layout shifts
    11. GIF Replacements and background video
    12. SVGs and icons
    13. SVG backgrounds
    14. Adding noise to images
    15. Asset caching on GitHub Actions
    16. Putting everything together
    17. Other useful systems

Improvements over Astro's Image and Picture Components

4m:58s

I’ve made lots of improvements over Astro’s Image and Picture components, so much so that I’ve built an Image component of my own to house those changes.

You can use it like this:

index.astro
---
import { Image } from '@splendidlabz/astro'
---
<Image src="/src/assets/penguin.png" alt="penguin" />

Below, I’m going to detail all of the changes I made — and why — so you understand why it’s necessary to build a custom image component over using built-in Image and Picture.

Problems and Improvements

There are a couple of problems with Astro’s Image and Picture components.

A better importing process

Here’s the first problem. You need to import an image before you can use it. It means you have to write the import statement multiple times if you have multiple images.

This can be a rather tedious process.

index.astro
---
import { Image } from 'astro:assets'
import image1 from '../assets/image1.png'
import image2 from '../assets/image2.png'
import image3 from '../assets/image3.png'
---
<Image src={image1} ... />
<Image src={image2} ... />
<Image src={image3} ... />

I very much prefer the standard way of writing images — where you just write the image’s path into the src.

Upon further testing, I discovered something that Astro doesn’t document — you can import the file directly into the src. This is slightly better than the above, but it’s still not a nice approach.

index.astro
---
import { Image } from 'astro:assets'
---
<Image src={import('../assets/image1.jpg')} alt="..." />
<Image src={import('../assets/image2.jpg')} alt="..." />

Writing the image path into src is not a trivial process — you need to build a custom image importer (to find the image), then pass the image into Astro’s Image or Picture component.

Here’s an example of this component in its simplest form.

CustomImage.astro
---
import { Image } from 'astro:assets'
const images = import.meta.glob('/src/assets/**/*.{jpeg,jpg,png,gif,avif,webp}')
const { src, ...rest } = Astro.props
// Building a custom importer
const key = Object.keys(images).find(key => key.startsWith(src))
if (!key) throw new Error(`File ${src} not found`)
const file = await images[key]()
const image = file.default
---
<!-- Passing the image to Astro's Image component -->
<Image src={image} {...rest} />

Once you have done this, you will be able to import the image directly from /src/assets!

---
import Image from '@/components/CustomImage.astro'
---
<Image src="/src/assets/penguin.png" alt="..." />

The benefit of using an absolute path (/src/assets) is: you get path autocompletion in your code editor.

Setting widths automatically

Second, I think it’s a hassle to set widths for each image individually.

index.astro
<Image src={image1} widths={[400, 800, 1200]} ... />
<Image src={image2} widths={[400, 800, 1200]} ... />
<Image src={image3} widths={[400, 800, 1200]} ... />

Since we already need to create a custom image component, why not add the default widths values into it as well?

CustomImage.astro
---
import { Image } from 'astro:assets'
// ...
const { src, widths = [400, 800, 1200, 1600], ...rest } = Astro.props
// ...
---
<!-- Passing the image to Astro's Image component -->
<Image src={image} {widths} {...rest} />

This is great since we no longer need to write widths when we use each Image.

index.astro
<Image src={image1} alt="..." />
<Image src={image2} alt="..." />
<Image src={image3} alt="..." />

But there’s a small problem with our hardcoded widths. It remains an invisible problem until you check the output carefully.

Let’s say you have an image at 2560px. Since we only wrote [400, 800, 1200, 1600] into widths, Astro does not wire up the original image into the srcset. Just look at the output and you’ll see this problem.

img output with a srcset containing only 400, 800, and 1200 pixel versions — the original 2560 pixel image is missing

To fix this, we need to get the original image’s width and append that to widths. We also need to filter values that are bigger than the original image.

CustomImage.astro
---
import { Image } from 'astro:assets'
// ...
const { src, widths = [400, 800, 1200, 1600], ...rest } = Astro.props
// ...
const image = file.default
const finalWidths = [...widths, image.width].filter(
width => width <= image.width,
)
---
<Image src={image} widths={finalWidths} {...rest} />

Adding Image Formats

Since Astro’s Picture is a superset of its Image component, we can provide formats for free by using the Picture component instead.

CustomImage.astro
---
import { Picture } from 'astro:assets'
// ...
const {
src,
widths = [400, 800, 1200, 1600],
formats = ['avif', 'webp'],
...rest
} = Astro.props
// ...
---
<!-- Passing the image to Astro's Picture component -->
<Picture src={image} {formats} {widths} {...rest} />

Figure and Figcaption

Some images have captions, some don’t. This creates styling problems because one image is encapsulated in figure while the other isn’t.

Instead of fretting over whether to style figure, picture or img tags, I wrapped all images in figure even if they don’t have captions. Then, for those with captions, we can always add and style the captions separately.

CustomImage.astro
---
import { If } from '@splendidlabz/astro'
// ...
const {
src,
caption = '',
widths = [400, 800, 1200, 1600],
formats = ['avif', 'webp'],
...rest
} = Astro.props
// ...
---
<!-- Passing the image to Astro's Picture component -->
<figure>
<Picture src={image} {formats} {widths} {...rest} />
<If condition={caption}>
<figcaption>{caption}</figcaption>
</If>
</figure>

All of these fixes built into Splendid Astro’s Image Component

The Image component I introduced to you above contains all of these fixes and more.

So you just gotta write this:

---
import { Image } from '@splendidlabz/astro'
---
<Image src="/src/assets/image.png" alt="image" />

And you get the figure + picture output:

<figure>
<picture>
<source srcset="..." type="image/avif" />
<source srcset="..." type="image/webp" />
<img
src="..."
srcset="..."
alt="..."
width="..."
height="..."
loading="lazy"
decoding="async"
/>
</picture>
</figure>

You can also disable the figure wrapping or use Image over Picture if you need to. Check the documentation for more information.