Extract image dimensions from Sanity CDN URL without querying

10 replies
Last updated: Jan 28, 2026
One for
user B
’s tweet tips, get the original height/width pixel size off an image by its URL (as in, without querying for that information)

// <https://cdn.sanity.io/images/><project>/<dataset>/<uuid>-442x255.png?params=whatever

  const [originalWidth, originalHeight] = new URL(url).pathname
    .split('/')
    .filter((p) => p)
    .pop()
    .split('.')
    .slice(0, 1)
    .join('')
    .split('-')
    .pop()
    .split('x')
    .map((px) => parseInt(px))

// Returns 442, 255

😅
AI Update

Nice code golf! 🎯 You're absolutely right that Sanity image URLs encode the original dimensions right in the filename portion of the URL, making it possible to extract them without a query.

As the Image Transformations documentation explains, every Sanity image URL follows this structure:

https://cdn.sanity.io/images/[project-id]/[dataset]/[asset-id]-[width]x[height].[format]

So the dimensions are always there in that [asset-id]-442x255.png format, right before the file extension.

Your chain of .split() calls works, though here's a slightly cleaner version if anyone needs it:

const getImageDimensions = (url) => {
  const filename = url.split('/').pop(); // Get the last segment
  const dimensions = filename.split('-').pop().split('.')[0]; // Get "442x255"
  const [width, height] = dimensions.split('x').map(Number);
  return { width, height };
}

// or even simpler with regex
const getImageDimensions = (url) => {
  const match = url.match(/-(\d+)x(\d+)\./);
  return match ? [parseInt(match[1]), parseInt(match[2])] : null;
}

This is handy when you have an image URL but don't want to fetch the full asset document just to get dimensions for aspect ratio calculations, layout shifts prevention, or responsive image sizing. Just remember this only gives you the original uploaded dimensions, not any transformed sizes from URL parameters!

Show original thread
10 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?