Get original image dimension with JavaScript

3

I have an image uploaded to my HTML page within the tag <img> , is there any way to know its original file size by JavaScript >?

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

  

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

    
asked by anonymous 22.09.2017 / 16:18

3 answers

3

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

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

A practical application would look like this:

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"/>

WithnaturalHeightandnaturalWidth:

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" />
    
22.09.2017 / 16:28
1

Searching I found the following cod:

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

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

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

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

With this command you get the original image sizes independent of the DOM

    
22.09.2017 / 16:34
-1

You can do 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">
    
22.09.2017 / 16:22