Get dimensions (and scale) an image in javascript

Load an image using new Image() and when onload is called the image will have width and height properties.

You can divide a max height by the actual height, if it's bigger, to get a ratio of the excess size, and multiple the height and width by that to resize the image.

We do all this, and wrap it in a Promise, below.

function dimensions_from_image(url, max_height=300, 
  max_width=600) {
  return new Promise((res, rej) => {
    var img = new Image();
    img.onerror = e => rej(e)
    img.onload = () => {
      var height = img.height;
      var width = img.width;
      if (height >= max_height) {
        var ratio = max_height / height
        height = height * ratio
        width = width * ratio
      }
      if (width >= max_width) {
        var ratio = max_width / width
        width = width * ratio
        height = height * ratio
      }
      res([width, height])
    }
    img.src = url
  })
}

It's called via

dimensions_from_image("the url")
.then(([width, height]) => {
  // do something
})
.catch(e => {
  // uh oh
})
javascript

Edit on github
comments powered by Disqus
Click me