Height x Width - Javascript - External Image

Asked

Viewed 595 times

2

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

2 answers

2


Can use new Image (https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image)

To get the original image width and height use:

  • naturalWidth
  • naturalHeight

As described in https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement

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 take 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>

1

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

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>

Browser other questions tagged

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