Sanity: Make it possible to get width and height from imageUrlBuilder

Created on 26 Nov 2019  路  3Comments  路  Source: sanity-io/sanity

Is your feature request related to a problem? Please describe.
When for example lazy loading and/or animating images on a website, you often need to specify the width _and_ height of the image.

This is currently hard/impossible to do when using the imageUrlBuilder from @sanity/image-url because you don't know what actual dimensions the image will have when it comes back after resizing and cropping.

For example in this case, I would only know the width, and not the resulting height:

          <img
            key={project.image.asset._ref}
            src={imageUrlBuilder(config).image(project.image)
              .width(400)
              .format('jpg')
              .auto('format')
              .quality(80)
              .url()}
          />

You can get the _original_ width and height from the asset ref, but that doesn't really help because the image may have been cropped, and being resized it won't be correct anyways.

Describe the solution you'd like
I'd like a an alternative to .url() named .props() which returned an object with src, height, and width, where height and width was calculated the exact same way as the Sanity image API does, meaning the height and width would match the exact height and width of the image returned from the url. Returning an object like that means you could both access the height and width as you want, but also that you could easily spread it directly onto an img tag:

          <img
            key={project.image.asset._ref}
            {...imageUrlBuilder(config).image(project.image)
              .width(400)
              .format('jpg')
              .auto('format')
              .quality(80)
              .props()}
          />

Describe alternatives you've considered
Calculating the resulting height and width manually would be both hard and error-prone. Don't even know how I'd begin to do that with all the hotspot, crop, and size parameters... 馃槙

Feature Request

Most helpful comment

This is an interesting suggestion. We'll look into it when we iterate on the image-url builder!

All 3 comments

This is an interesting suggestion. We'll look into it when we iterate on the image-url builder!

Bump.

Would love to have this feature too.

function croppedDimensions(height, width, crop, croppedWidth){
  if(crop){
    const y = crop.top + crop.bottom
    const x = crop.left + crop.right
    height = (1-y) * height
    width = Math.round((1-x) * width)
  }
  height = croppedWidth ? Math.round(height * croppedWidth / width) : Math.round(height)
  return {height, width: croppedWidth ?? width}
}

You can use this function to get the height and width. Where "crop" is the crop object stored in a sanity image. Rest of the values are in pixels.

Was this page helpful?
0 / 5 - 0 ratings