How to find the resolution of an Image in JavaScript

We can get the original height and width of the image, this height and weight of the image is the actual size of an image without any constraints. Constraints like explicitly mentioning the height and width of the or placing image in the container that limits its size.

Finding the resolution of an image in Javascript

We will be using naturalHeight and naturalWidth properties to get the size.

The height and width are returned in pixels.

In our HTML, we define our image

<img src="C:\\Users\\LENOVO\\Desktop\\Resolution\\22.png" id="imgId">

In the script tag, we get the image by the id specified in our image tag and add an event listener that is triggered on page load so that we don’t get an error if the image isn’t loaded when we try to get the height and width.

let img = document.getElementById('imgId');
      img.addEventListener('load',imgSiz)

In imgSiz() function,

function imgSiz() {
        let w = img.naturalWidth;
        let h = img.naturalHeight;
        console.log("Original width=" + w + " px, " + "Original height=" + h+" px");
      }

The width will be assigned to variable w and height to variable h. The output is displayed in the console log of devTools.

Here’s the complete code,

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Resolution</title>
    
  </head>
  <body>
    <img src="C:\\Users\\LENOVO\\Desktop\\Resolution\\22.jpg" id="imgId">
    
    <script>
       let img = document.getElementById('imgId');
       img.addEventListener('load',imgSiz)
      function imgSiz() {
        let w = img.naturalWidth;
        let h = img.naturalHeight;
        console.log("Original width=" + w + " px, " + "Original height=" + h+" px");
      }

    </script>
  </body>
</html>

Output

How to find the resolution of an Image in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *