Joint session with Vercel: How to build intelligent storefronts (May 15th)

Get image ratio without GROQ query using @sanity/image-url helper

14 repliesLast updated: Nov 29, 2025

Hi guys, i was wondering if there is a way to get the original image ratio without adding it to the GROQ query. I’d like to know the ratio of the image without restricting the content managers too much by fixing them in the schema. We’ve used the GROQ way before, like this:
const query = `*[_type == "solutions-singleton"] {
  ...,
  "platformsImage": fields.platforms.platformsImage.asset->{
    url,
    metadata {
      dimensions
    }	
  },
}`
but this doesn’t seem very scalable. Is there a way to get the ratio of the image by using, for example, the
@sanity/image-url
helper?
AI Update

Good news! You don't need to query for dimensions in GROQ every time. The image asset _id actually contains the dimensions encoded in its format, and @sanity/image-url already parses this information internally.

The asset _id follows this pattern:

image-<sha1hash>-<width>x<height>.<extension>

So you can extract the dimensions directly from the asset reference without expanding it in your GROQ query. Here's how:

// Your GROQ query can just be:
const query = `*[_type == "solutions-singleton"] {
  ...,
}`

// Then in your code:
function getImageDimensions(imageAsset) {
  // imageAsset._ref will be something like:
  // "image-abc123-1920x1080-jpg"
  const dimensions = imageAsset._ref.split('-')[2];
  const [width, height] = dimensions.split('x').map(Number);
  const aspectRatio = width / height;
  
  return { width, height, aspectRatio };
}

Even better, if you're already using @sanity/image-url, it parses these dimensions internally through its parseAssetId function. While it doesn't expose a direct method to retrieve the ratio, you could:

This approach is much more scalable than projecting metadata in GROQ since:

The dimensions are already there in the asset ID - you just need to parse them!

Show original thread
14 replies

Was this answer helpful?

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.

Related contributions