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