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/>&lt;project&gt;/&lt;dataset&gt;/&lt;uuid&gt;-442x255.png?params=whatever

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

// Returns 442, 255

😅
Apr 2, 2021, 12:02 PM
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/>&lt;project&gt;/&lt;dataset&gt;/&lt;uuid&gt;-442x255.png?params=whatever"
})
Apr 2, 2021, 12:09 PM
Boooo
Apr 2, 2021, 12:20 PM
No fun allowed, I love writing my own absurd one-liners
Apr 2, 2021, 12:21 PM
😂
Apr 2, 2021, 12:22 PM
I'm a fan, too! It's my 6-months-from-now self that hates it 😂
Apr 2, 2021, 12:30 PM
Yes, well I’ve installed that library now and my code is 20 lines lighter 😄
Apr 2, 2021, 12:30 PM
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)
Apr 2, 2021, 2:14 PM
Now we’re talking
Apr 2, 2021, 2:20 PM
I want to start an “obtuse and ill advised sanity tips” Twitter thread.
Apr 2, 2021, 2:21 PM
aka diwhy
Apr 2, 2021, 9:27 PM

Sanity.io – build remarkable experiences at scale

Sanity is a customizable solution that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Categorized in