Height x Width - JavaScript - External Image

2

I need to get the height and width value of an external image, with Javascript / Jquery, that is, without being implemented in the image code.

    
asked by anonymous 08.12.2017 / 02:54

2 answers

2

You can use new Image ( link )

To get the original width and height of the image use:

  • naturalWidth
  • naturalHeight

As described in link

Example:

function getImageSize(url, success, error) {
    var img = new Image;
    img.onload = function () {
        success(img.naturalWidth, img.naturalHeight);
    };
    img.onerror = error;
    img.src = url;
}

getImageSize("https://i.stack.imgur.com/ShnZP.png?s=328&g=1", function (largura, altura) {
   console.log("largura: " + largura, "altura: " + altura);
}, function () {
   console.log("Erro ao carregar a imagem");
});

getImageSize("https://cdn.sstatic.net/Sites/br/img/sprites.svg?v=554232ea0d79", function (largura, altura) {
   console.log("largura: " + largura, "altura: " + altura);
}, function () {
   console.log("Erro ao carregar a imagem");
});

If you want to get the size of an image already inserted in the page, you can use document.getElementByID or document.querySelector (depends on how the image is), for example:

function getHtmlImageSize(img, success, error) {
    if (img.complete) {
         complete();
         return;
    }

    img.addEventListener("error", fail);
    img.addEventListener("load", complete);

    function complete() {
         if (img.naturalWidth) {
             success(img.naturalWidth, img.naturalHeight);
         } else {
              error();
         }
         finish();
    }

    function fail() {
         error();
         finish();
    }

    function finish() {
        img.removeEventListener("error", error);
        img.removeEventListener("load", complete);
    }
}

//Pega a imagem no HTML
var img1 = document.querySelector(".some-class > img");

getHtmlImageSize(img1, function (largura, altura) {
   console.log("largura: " + largura, "altura: " + altura);
}, function () {
   console.log("Erro ao carregar a imagem");
});
<div class="some-class">
    <img src="https://i.stack.imgur.com/ObF0n.gif">
</div>
    
08.12.2017 / 04:21
1

As I replied in SOEN , you can use jQuery, doing the following:

var src = 'https://i.stack.imgur.com/RWWpy.png';

$('<img>').attr({src: src}).on('load', function () {
    console.log(this.naturalHeight);
    console.log(this.naturalWidth);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
14.12.2017 / 14:54