Get Image Width and Height using JavaScript

Get Image Width and Height using JavaScript

In this tutorial we will see how to Get Image Width and Height using JavaScript, Two JavaScript properties .naturalWidth and .naturalHeight are used for this.

HTML Code

HTML Code is given below.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Image Width and Height using JavaScript</title>
</head>
<body>
<img src="bg.png" id="image">
<button onclick="getSize();">Get Image Width and Height</button>
</body>
</html

JavaScript Code

JavaScript Code is given below, In this code we have used naturalWidth and naturalHeight properties to get the original width and height of the image.

<script>
function getSize(){
var img = document.querySelector("#image");
var width = img.naturalWidth;
var height = img.naturalHeight;
alert("Image Width=" + width + " & " + "Image Height=" + height);
}
</script>

Demo

Video Tutorial

Watch video tutorial on how to Get Image Width and Height using JavaScript.

Post a Comment

Previous Post Next Post