Get the Original Height/Width Pixel Size of an Image by its URL
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 thread10 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.