#How to use content collection image with getImage()

3 messages · Page 1 of 1 (latest)

rancid hedge
#

I'm a little confused about what the src field should be when passed to the getImage() function.

I'm using an image field from a content collection (not imported directly). It has a structure like this:

{
src: {
src: '/@fs/Users/.../black-standard-painting.png?origWidth=1792&origHeight=1024&origFormat=png',
width: 1792,
height: 1024,
format: 'png',
fsPath: '/Users/.../black-standard-painting.png'
},
alt: "The ... Study Resources"
}

When I try to generate a new image (for my og fields) with getImage, what src value shoudl I use? passing the image object errors, passing the image.src.src errors and passing the image.src.fsPath works -- but the resulting URL is a 404 on production (Vercel). How should I be generating image URLS in this case?

iron archBOT
#

Hi @rancid hedge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

When using getImage() with an image from a content collection, you should pass the src property of the image object to the src parameter of getImage().

Here's an example of how you might do this:

import { getImage } from "@astrojs/image";

const { src: imageSrc } = post.data.cover; // Assuming post.data.cover is your image object from the content collection

const { src: optimizedImageSrc } = await getImage({
    src: imageSrc,
    width: 20,
    aspectRatio: 16/9,
    format: "jpg"
});

In this example, post.data.cover is the image object from the content collection, and imageSrc is the src property of that object. This imageSrc is then passed to getImage().

However, please note that getImage() relies on server-only APIs and breaks the build when used on the client. It is intended for generating images destined to be used somewhere else than directly in HTML, for example in an API Route. It also allows you to create your own custom <Image /> component.

If you're still encountering issues, it might be due to the specific setup or configuration of your project. In that case, it would be best to refer to the Astro documentation (https://docs.astro.build/) or seek help from the Astro community.

Sources:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: