Get original image dimension with Javascript

Asked

Viewed 1,863 times

3

I have an image uploaded to my HTML page inside tag <img>, there is some way to know size of her original archive by Javascript?

Let’s say I want to give one console.log(larguraImagem, alturaImagem);.

Note that the size I want to know is the original that is in server and not what is being displayed on the screen because this may be being resized by CSS.

3 answers

3


I believe the only cross-browser way that includes older browsers is asynchronous, creating a new image with the builder new Image.

For modern browsers you can use the naturalHeight and naturalWidth (example below)

A practical application would thus be:

function getImgSize(image) {
  const newImg = new Image();
  return new Promise((res, rej) => {
    newImg.onload = function() {
      const height = newImg.height;
      const width = newImg.width;
      res({
        width: newImg.width,
        height: newImg.height
      });
    }
    newImg.src = image.src;
  });
}

const img = document.querySelector('img');
getImgSize(img).then(size => console.log(size));
img {
  width 10%;
}
<img src="https://cdn.pixabay.com/photo/2016/08/02/23/05/sunrise-1565344_960_720.jpg" />

With naturalHeight and naturalWidth:

function getImgSize(image) {
  return {
  width: image.naturalWidth,
  height: image.naturalHeight
  }
}

const img = document.querySelector('img');
const size = getImgSize(img);
console.log(size);
img {
  width 10%;
}
<img src="https://cdn.pixabay.com/photo/2016/08/02/23/05/sunrise-1565344_960_720.jpg" />

  • 1

    Excellent reply! Thank you.

1

Searching found the following Cod:

var img = document.getElementById('imageid'); 

var width = img.clientWidth;
var height = img.clientHeight;

only that it will return its size according to the DOM that is the size of it displayed in your browser ( this is influenced by css ) to resolve this you must use the following command:

var originalwidth = img.naturalHeight;
var originalheight = img.naturalWidth;

with this command you take the original image sizes regardless of the DOM

-1

You can do it like this...

let imagem = document.getElementById('imagem') 

let width = imagem.clientWidth;
let height = imagem.clientHeight;

alert(width + ' - ' + height)
<img src="http://cdn2.thr.com/sites/default/files/imagecache/card_landscape_930_524/2017/08/courtesy_of_hbo_photo_11-h_2017.jpg" id="imagem">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.