Open Svish opened 4 years ago
Yep, same here. Next.js for example expects values for height
and width
in order to serve the image with its <Image />
component (next/image). At the moment I'm extracting the expected values from the URL that's comes back from urlFor.url()
.
I would love to get other information about the image such as filename too
@ralphbolliger was this ever actioned?
FWIW, I've used a combination of approaches with Next.js:
Here's what I drop in (and reuse) within all my queries:
const imageQuery = groq`
"src": asset->url,
alt,
"width": asset->metadata.dimensions.width,
"height": asset->metadata.dimensions.height,
"blurDataURL": asset->metadata.lqip
`;
In a query:
export const postQuery = groq`
title,
excerpt,
featuredImage {
${imageQuery}
}
`;
And then with Next.js Image:
<Image {...post.featuredImage} />
Especially when using lazy loading or transition libraries, it's often crucial to set the width and height of an image. With the magic happening with resizing, cropping, focal points, etc., it feels kind of difficult to do that correctly when using this url builder and the Sanity CDN for images.
I suggest you add an alternative to
.url(): string
, for example.props(): { url: string, width: number, height: number }
. One could then just spread those props onto an<img>
tag, and if needed also use thewidth
andheight
values for calculations or whatever.Note that even if one has only supplied one of height or width, the returned object should always include both, and they should match what will come back from the Sanity CDN.
Tried looking into it myself, and was kind of hopeful when I found https://github.com/sanity-io/image-url/blob/master/src/urlForImage.ts#L198-L201, but then realized the
fit
function isn't actually always used, so one would still have to potentially calculate a width and/or height to return in those cases. And that calculation should match whatever is happening in the CDN when its only asked for a width or a height. But haven't been able to find the source for that, so... 😕Either way, would probably be better if someone in the Sanity team did this, who's a bit more familiar with the code and the backend and everything. 🤔