Obtain the dimensions of an image in Javascript

3

Can JavaScript get the size of the image? that is, if it is in a web element image with width and height you get what it takes to screen, but I'm interested to know what is its actual size.

    
asked by Webserveis 09.06.2017 в 11:02
source

2 answers

4
<script>
foto=new Image();
foto.src="Imagen.jpg";
document.images[0].src=foto.src;
ancho=foto.width;
alto=foto.height;

alert(ancho)
alert(alto)
</script>

That's the same thing for you

    
answered by 09.06.2017 / 11:03
source
5

Since HTML5 you have available the naturalWidth and naturalHeight attributes: Source

Example

<img src="https://s-media-cache-ak0.pinimg.com/736x/de/c2/3a/dec23ae0053c5b58175898dcfe2e7210.jpg" width="300" height="300">

<script>
    var img = document.querySelector('img');
    var altoDefinido = img.height; // 300
    var altoOriginal = img.naturalHeight; // 600
    var anchoDefinido = img.width; // 300
    var anchoOriginal = img.naturalWidth; // 600
</script>
    
answered by 09.06.2017 в 11:19