/    Sign up×
Articles /Pin to ProfileBookmark

Optimize a Folder of Images with Astro 3.0

Astro 3.0 was just released and it comes with a great image compression feature. The savings can be up to 99.1% less data based on testing I did with compressing .jpg images directly from a camera. However, all the examples only show how to compress and import one image at a time. In this blog post, I’ll show you how to use Astro’s built-in Image component to optimize all images in a folder with just a few lines of code. If you haven’t done so already, create an Astro project and start a new component.

Importing Components

First, you need to import the Image component from astro:assets. This component will automatically compress and lazy load your images for the best quality and speed.

Writing the Script

Next, you need to use Astro.glob to import all your image files at once. This is a handy method that returns an array of files matching a glob pattern. You can use any valid glob pattern to filter the files by extension, name, or subfolder. For example, "../assets/images/*.{jpg,JPG,jpeg,png,PNG,webp}" will get all the .jpg.png and .webp files from the ../assets/images/ folder.

Finally, the images.map function loops over the array of files and renders each one to its own Image component.

Full Code Example:

---
import { Image } from "astro:assets";

const images = await Astro.glob(
 "../assets/images/*.{jpg,JPG,jpeg,png,PNG,webp}"
).then((files) => {
 return files.map((file) => file.default); // Map each file to its default export (the src).
});
---

{
 images.map((img) => (
 <Image
 src={img}
 width="1200"
 height="750"
 />
 ))
}

That’s it! Now you have optimized all your images with Astro 3.0 and improved your website performance.

Back-endFull-stack DeveloperNode.jsSEO
×

Success!

Help @threehymns spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 11.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @bahaedd,
tipped: article
amount: 1000 SATS,

tipper: @Balmasexy,
tipped: article
amount: 1000 SATS,

tipper: @mbsaad,
tipped: article
amount: 1000 SATS,
)...