How to Get Image Size Using JavaScript
You can get the original width and height of an image using the HTML5 image naturalWidth and naturalHeight properties, which are supported in almost all major browsers.
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<div>Click on img to see the result</div>
<script>
let img = document.createElement('img');
img.id = 'imgId';
img.src = '/uploads/media/default/0001/05/e9f3899d915c17845be51e839d5ba238f0404b07.png';
document.body.appendChild(img);
img.addEventListener("click", imgSize);
function imgSize() {
let myImg = document.querySelector("#imgId");
let realWidth = myImg.naturalWidth;
let realHeight = myImg.naturalHeight;
alert("Original width=" + realWidth + ", " + "Original height=" + realHeight);
}
</script>
</body>
</html>
To get the current width and height, you can use the JavaScript clientWidth and clientHeight properties. These are DOM properties that show the current in-browser size of the inner dimensions of a DOM element, excluding margin and border.
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<style>
img {
margin: 20px;
}
</style>
</head>
<body>
<div>Click on img to see the result</div>
<script>
let img = document.createElement('img');
img.id = 'imgId';
img.src = 'https://pbs.twimg.com/profile_images/1144166476682813440/o23kohmr_400x400.png';
document.body.appendChild(img);
img.addEventListener("click", imgSize);
function imgSize() {
let img = document.getElementById('imgId');
//or however you get a handle to the IMG
let width = img.clientWidth;
let height = img.clientHeight;
alert("Original width=" + width + ", " + "Original height=" + height);
}
</script>
</body>
</html>
The naturalWidth and naturalHeight Properties
The naturalWidth and naturalHeight are read-only properties that return the original width and height of an image, respectively. As the width and height of an image displayed on the webpage can be altered using the ‘width’ and ‘height’ attributes of the <img> tag, the naturalWidth and naturalHeight properties are used in situations where original width or height of the image is required.