How to Get Image Dimensions in Javascript

In this tutorial, you will learn how to get image dimensions in javascript. Whenever we want to display an image, we make use of the img element.  This source of the image can be a relative URL or absolute URL.

The img element has a bunch of useful attributes such as height and width to manipulate the dimensions of an image.  The image dimensions can also be changed using CSS.  The point to be noted here is that image size depends upon the extension of the image as well as its dimensions.

You may have seen websites where they restrict users to upload images only of certain dimensions. To apply those restrictions, they have to detect the image dimensions using javascript before going forward with the upload process.

The img element has naturalHeight and naturalWidth properties.  These properties return the actual dimensions of the image.  We can take advantage of these properties to accomplish our goal.

In the following example, we have one img element and one button element.  Upon click of a button, we will get the original dimensions of the image and display that on the screen. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 4 elements in the HTML file (button, span, hr, and img).
  • The span element is empty as of now. We will display the dimensions of the image in it using javascript.
  • The button element has “Get Size” as innerText.
  • We are using background.jpg as a source of the img element. You can use any image of your choice.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <button>Get Size</button>
    <span id="size"></span>
    <hr>    
    <img src="background.jpg" alt="" style="height:250px; width:250px;">
    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have selected button, img, and span elements using the document.querySelector() method and stored them in the btn, span, and img variables respectively.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are getting image dimensions using the naturalHeight and naturalWidth property of the img element and displaying that in the span element using the innerText property.
let btn = document.querySelector('button');
let span = document.querySelector('#size');
let img = document.querySelector('img');

btn.addEventListener('click', () =>{
    span.innerText = `Height: ${img.naturalHeight} - Width: ${img.naturalWidth}`;
});
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •