👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

How to get the Width/Height or dimensions of Uploaded Image with Sanity and Next.js to Prevent CLS

3 replies
Last updated: Aug 9, 2021
not sure if this is what you’re looking for, but this thread might help? https://stackoverflow.com/questions/58567054/how-can-i-validate-the-dimensions-of-an-uploaded-image-in-sanity
Aug 9, 2021, 5:56 PM
there’s a really nice regex + function combo there you can use to snip the dimensions from
asset._ref


const pattern = /^image-([a-f\d]+)-(\d+x\d+)-(\w+)$/

const decodeAssetId = id => {
  const [, assetId, dimensions, format] = pattern.exec(id)
  const [width, height] = dimensions.split("x").map(v => parseInt(v, 10))

  return {
    assetId,
    dimensions: { width, height },
    format,
  }
}
Aug 9, 2021, 6:13 PM
there’s a really nice regex there you can use to snip the dimensions from
asset._ref
Aug 9, 2021, 6:13 PM
Aug 9, 2021, 6:48 PM

Sanity– build remarkable experiences at scale

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

Was this answer helpful?