Calculate dimensions of an image using jQuery

1

I would like to know how to calculate the size (width and height) of several images using jquery, I would like to validate those sizes. This is the script that I have up to.

/*jQuery*/
var ancho;
var alto;
$("img").each(function(){
  ancho = $(this).width();
  alto = $(this).height();

  if(ancho < alto)
    console.log("Es más ancha");
  else if(ancho > alto)
    console.log("Es más alto");
  else
    console.log("Es una imagen cuadrada");
});

This is the HTML code

<!--HTML-->
<img src="imagen1.jpg">
<img src="imagen2.jpg">
<img src="imagen3.jpg">
    
asked by Danielle Lewis 25.10.2017 в 20:20
source

1 answer

3

I do not see any problem with your code. The only thing that occurs to me is that you are trying to measure the images before they have finished loading.

To handle that you can run the measurement when they finish loading using the load event. Peeero ... As it can happen that the image loads before you declare the listener about the event, you can also add a check on the property complete of the image, forcing it to emit an event load that jQuery can detect.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img id="cuadrado" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAASElEQVR42u3PQREAMAgAoNlhtewfwRiawa8HDYhf2e+AEBERERERERERERERERERERERERERERERERERERERERERERERERHZGA3lchHmrzGHAAAAAElFTkSuQmCC">


<img id="vertical" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAA8CAYAAAAUufjgAAAAR0lEQVR42u3OAQ0AMAgAoNvhMexfyRhawzlIQOSvfouFoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKDgveAAMq6BJbaAYxwAAAAASUVORK5CYII=">

<img id="horizontal" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAoCAYAAACiu5n/AAAARUlEQVR42u3PMQEAMAgAoNlht/2bGUNb+AgNiMrf75AQFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhbeNfkSU+klXpjsAAAAAElFTkSuQmCC">


<script>
$(document).ready(function() {

$("img").one("load", function() {
  var ancho = $(this).width(),
  alto = $(this).height();

  if(ancho > alto)
    console.log(this.id,"Es más ancha");
  else if(ancho < alto)
    console.log(this.id,"Es más alto");
  else
    console.log(this.id,"Es una imagen cuadrada");
}).each(function() {
  if(this.complete) {
    $(this).load();
  } 
});
 

});
</script>
    
answered by 25.10.2017 / 20:47
source