Get the Original Height/Width Pixel Size of an Image by its URL

10 replies
Last updated: Apr 2, 2021
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
Great tip!
To make this easier, lean on
@sanity/asset-utils :
import {getImageDimensions} from '@sanity/asset-utils'

const { aspectRatio, height, width } = getImageDimensions({
  url: "<https://cdn.sanity.io/images/><project>/<dataset>/<uuid>-442x255.png?params=whatever"
})
Boooo
No fun allowed, I love writing my own absurd one-liners
😂
I'm a fan, too! It's my 6-months-from-now self that hates it 😂
Yes, well I’ve installed that library now and my code is 20 lines lighter 😄
Why not use regex?
const [w, h] = image_url.match(/(\d{1,})(?=\.|\x)/g);
(though it may match part of the hash so the url has to be split first)
Now we’re talking
I want to start an “obtuse and ill advised sanity tips” Twitter thread.
aka diwhy

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?