Get image aspect ratio from Sanity image URL builder

6 replies
Last updated: Jan 28, 2026
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.
AI Update

The good news is that you absolutely can get the dimensions from a Sanity image to set proper width and height attributes! The @sanity/asset-utils package has a dedicated function called getImageDimensions that extracts the width, height, and aspect ratio from your image asset.

Here's how it works:

import {getImageDimensions} from '@sanity/asset-utils'

// Works with any of these formats:
const dimensions = getImageDimensions(image)
// Returns: { width: 1920, height: 1080, aspectRatio: 1.777... }

The beauty of this function is that it accepts any inferrable structure - image objects, asset documents, references, IDs, URLs, or paths. The dimensions are actually encoded in the asset ID itself (like image-abc123-1920x1080-jpg), so this is a synchronous operation that doesn't require any API calls.

Practical Example with Next.js Image

import Image from 'next/image'
import {getImageDimensions} from '@sanity/asset-utils'
import {urlFor} from './sanity' // your image URL builder

function MyImage({image}) {
  const {width, height} = getImageDimensions(image)
  
  return (
    <Image
      src={urlFor(image).url()}
      alt={image.alt}
      width={width}
      height={height}
      // The intrinsic aspect ratio is preserved automatically!
    />
  )
}

If You Need Just the Aspect Ratio

The function returns an aspectRatio property too, which you can use for CSS:

const {aspectRatio} = getImageDimensions(image)

<div style={{aspectRatio}}>
  <img src={urlFor(image).url()} alt="" />
</div>

Important Note

As mentioned in the @sanity/asset-utils documentation, this package only works with information already encoded in the asset reference. It won't fetch metadata like LQIP, blurhash, or color palette - you'd need to query those from the Sanity API using image metadata fields if needed.

The dimensions are always available though, since they're part of the asset ID structure that Sanity uses for all images!

Show original thread
6 replies

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?