Get image width and height with @sanity/image-url

1 replies
Last updated: Oct 5, 2021
Is there a way to get the image width and height via the
@sanity/image-url
package?
AI Update

The @sanity/image-url package itself doesn't provide methods to get image dimensions - it's focused on building image transformation URLs. However, you can easily extract width and height from Sanity image assets using the @sanity/asset-utils package.

Using @sanity/asset-utils

Install the package:

npm install @sanity/asset-utils

Then use getImageDimensions():

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

const dimensions = getImageDimensions(imageAsset)
// Returns: { width: 1920, height: 1080, aspectRatio: 1.777... }

You can pass either:

  • The full image asset object
  • Just the asset reference (imageAsset.asset)
  • The asset _ref string

Why dimensions aren't in the metadata object

Sanity always includes dimensions metadata for every image automatically (along with hasAlpha and isOpaque), but these aren't stored in the metadata field you might see in your schema configuration. As explained in the image metadata documentation, dimensions are fundamental properties that can't be disabled.

The getImageDimensions() helper extracts this information from the asset's _ref ID, which encodes the dimensions in the format image-{id}-{width}x{height}-{format}. This means you don't even need to fetch the full asset document to get dimensions - the reference string contains everything you need.

Practical example with Next.js Image

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

const builder = imageUrlBuilder(client)

function MyImage({imageAsset}) {
  const {width, height} = getImageDimensions(imageAsset)
  
  return (
    <img
      src={builder.image(imageAsset).width(800).url()}
      width={width}
      height={height}
      alt="My image"
    />
  )
}

This approach helps prevent cumulative layout shift (CLS) by providing explicit dimensions to your image components.

Show original thread
1 reply
Not sure if there’s something in the
@sanity/image-url
package now, but I do know the width / height are always listed in the asset id:
"asset": {
  "_ref": "image-50ee4ebeb90531c90d2d383de12f2e973cd6fc71-800x1199-png",
  "_type": "reference"
}
So you can extract them from there

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?