Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?
Also (in addition to Rex and Ian's answers) there is:
imageElement.naturalHeight
and
imageElement.naturalWidth
These provide the height and width of the image file itself (rather than just the image element).
You can programmatically get the image and check the dimensions using Javascript...
const img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
This can be useful if the image is not a part of the markup.
clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
var imgSrc, imgW, imgH;
function myFunction(image){
var img = new Image();
img.src = image;
img.onload = function() {
return {
src:image,
width:this.width,
height:this.height};
}
return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
//Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
imgSrc = x.src;
imgW = x.width;
imgH = x.height;
});
x.addEventListener('load',function(){
console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.
This is my method, hope this helpful. :)
Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.
I found the following, as some have suggested, to be incorrect:
let img = new Image();
img.onload = function() {
console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";
This is correct:
let img = new Image();
img.onload = function() {
console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";
Conclusion:
Use img
, not this
, in onload
function.
Using JQuery you do this:
var imgWidth = $("#imgIDWhatever").width();