W3docs

How to Get Image Size Using JavaScript

Read this tutorial and learn the two methods of getting the width and height of the image. Learn about the properties that help to get the image size.

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.

Javascript get original width and height of an image

<!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';
      img.addEventListener('load', () => {
        img.addEventListener("click", imgSize);
      });
      document.body.appendChild(img);
      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, including padding but excluding margin and border.

Javascript get current width and height of an image

<!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';
      img.addEventListener('load', () => {
        img.addEventListener("click", imgSize);
      });
      document.body.appendChild(img);
      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("Current width=" + width + ", " + "Current 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 <kbd class="highlighted"> XFI2 </kbd> tag, the naturalWidth and naturalHeight properties are used in situations where original width or height of the image is required.