0
0
Astroframework~5 mins

Image optimization with astro:assets

Choose your learning style9 modes available
Introduction

Optimizing images makes websites load faster and look better on all devices. Astro's astro:assets helps do this automatically.

When you want your website images to load quickly on phones and computers.
When you need to serve different image sizes for different screen widths.
When you want to reduce the file size of images without losing quality.
When you want to use modern image formats like WebP for better performance.
Syntax
Astro
import { Image } from 'astro:assets';

<Image src="./path/to/image.jpg" alt="Description" width={300} height={200} />
Use the Image component from astro:assets to optimize images.
Specify src, alt, and size attributes like width and height.
Examples
Basic image with fixed width and height for a logo.
Astro
import { Image } from 'astro:assets';

<Image src="./logo.png" alt="Site Logo" width={150} height={50} />
Image optimized to use WebP format for better compression.
Astro
import { Image } from 'astro:assets';

<Image src="./photo.jpg" alt="Beautiful landscape" width={600} height={400} format="webp" />
Image with a blurred placeholder shown while loading.
Astro
import { Image } from 'astro:assets';

<Image src="./avatar.png" alt="User avatar" width={100} height={100} placeholder="blur" />
Sample Program

This Astro component imports the Image from astro:assets and displays an optimized image with a blurred placeholder. The image will load faster and look good on all devices.

Astro
---
import { Image } from 'astro:assets';
---

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Astro Image Optimization Example</title>
  </head>
  <body>
    <h1>Welcome to My Site</h1>
    <Image src="./sample-photo.jpg" alt="Sample Photo" width={800} height={600} placeholder="blur" />
  </body>
</html>
OutputSuccess
Important Notes

Always provide an alt attribute for accessibility.

Use the placeholder="blur" option to improve user experience during image loading.

Astro automatically creates multiple image sizes and formats for best performance.

Summary

Astro's astro:assets makes image optimization easy and automatic.

Use the Image component to serve optimized images with proper sizes and formats.

Adding placeholders and alt text improves accessibility and user experience.