Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get image size (height & width) using JavaScript?

Are there any JavaScript or jQuery APIs or methods to get the dimensions of an image on the page?

like image 710
Saneef Avatar asked Mar 08 '09 06:03

Saneef


People also ask

What is image height?

Description. The Image Height is one part of the information that determines a picture's, photo's or other image's dimension. Together with the image width, this value determines the size of an image itself, not the file size. Often, Image Height is given in pixels, e.g. 682 px.

How can I set the height and width of an image?

Example. The width attribute specifies the width of an image, in pixels. Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded.

How do you get the image width and height using JS?

Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.


2 Answers

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.

like image 116
Josh Stodola Avatar answered Oct 13 '22 22:10

Josh Stodola


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; 
like image 28
Rex M Avatar answered Oct 13 '22 22:10

Rex M