Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?
just pass the img file object which is obtained by the input element when we select the correct file it will give the netural height and width of image
function getNeturalHeightWidth(file) {
let h, w;
let reader = new FileReader();
reader.onload = () => {
let tmpImgNode = document.createElement("img");
tmpImgNode.onload = function() {
h = this.naturalHeight;
w = this.naturalWidth;
};
tmpImgNode.src = reader.result;
};
reader.readAsDataURL(file);
}
return h, w;
}
Recently I had same issue for an error in the flex slider. The first image's height was set smaller due to the loading delay. I tried the following method for resolving that issue and it's worked.
// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('<img id="testImage" />');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);
tempImg[0].onload = function () {
$(this).css('height', 'auto').css('display', 'none');
var imgHeight = $(this).height();
// Remove it if you don't want this image anymore.
$('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';
This will give you the height with respect to the width you set rather than original width or Zero.
With jQuery library-
Use .width()
and .height()
.
More in jQuery width and jQuery heigth.
$(document).ready(function(){
$("button").click(function()
{
alert("Width of image: " + $("#img_exmpl").width());
alert("Height of image: " + $("#img_exmpl").height());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
<button>Display dimensions of img</button>
You can also use:
var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
Before acquire element's attributes,the document page should be onload:
window.onload=function(){
console.log(img.offsetWidth,img.offsetHeight);
}
Simply, you can test like this.
<script>
(function($) {
$(document).ready(function() {
console.log("ready....");
var i = 0;
var img;
for(i=1; i<13; i++) {
img = new Image();
img.src = 'img/' + i + '.jpg';
console.log("name : " + img.src);
img.onload = function() {
if(this.height > this.width) {
console.log(this.src + " : portrait");
}
else if(this.width > this.height) {
console.log(this.src + " : landscape");
}
else {
console.log(this.src + " : square");
}
}
}
});
}(jQuery));
</script>