Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to Get the Aspect Ratio of an Image From the Image URL Builder Tool

6 replies
Last updated: Apr 21, 2022
Hi!
Is there a way to get the aspect ratio of an image from the image url builder tool? I want to specify the width and height of all my images to avoid layout shifting, but I can't really find a way to figure out the height, given that I want the image to preserve its intrinsic aspect ratio.
Apr 21, 2022, 8:02 AM
Could this link help you? I think that in your case you need to handle assets, and not an image url
https://www.sanity.io/docs/assets
Apr 21, 2022, 8:56 AM
More over, having width and height of the image you could calculate the aspect ratio.
https://www.omnicalculator.com/other/aspect-ratio
Apr 21, 2022, 8:58 AM
One solution would be to create the container for the image, within a div or a picture tag, and use the url as a background. So there you can specify height or the like.
A second solution might be to set the img tag in a div, and on the image tag you could use the css property object-fit: cover to not have any overflow or stretched image.
Apr 21, 2022, 9:07 AM
Hope it helped
user U
🙂
Apr 21, 2022, 9:07 AM
hm… well, thanks for putting me on the right track. Turns out, I can fetch the aspect ratio from an image with

image.asset->metadata.dimensions.aspectRatio
Apr 21, 2022, 9:25 AM
I see you found the answer! 🙂 We have a comprehensive article about image metadata in the docs if you have further needs in that regard!
Apr 21, 2022, 12:19 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?