Clue Mediator

How to get the original image size (width and height) using JavaScript

πŸ“…January 7, 2022
πŸ—JavaScript

Today we will show you how to get the original image size (width and height) using JavaScript. In the previous article, we have explained how to get current image size.

Checkout more articles on JavaScript

  • scroll-to-a-specific-element-using-javascript" title="Scroll to a specific element using JavaScript">Scroll to a specific element using JavaScript
  • Detect a mobile device using JavaScript
  • file-using-javascript" title="Download a file using JavaScript">Download a file using JavaScript
  • array-into-chunks-in-javascript" title="Split an array into chunks in JavaScript">Split an array into chunks in JavaScript

You can use the `API/HTMLImageElement/naturalWidth" title="naturalWidth">naturalWidth` and `naturalHeight` to get the current width and height of the image in pixel.

Refer to the sample HTML code below to get the image size.




<meta charset="utf-8">
<title>How to get original image size (width and height) using JavaScript - Clue Mediator</title>
<script>
  function getImgSize(){
    var myImg = document.querySelector("#myImage");
    var realWidth = myImg.naturalWidth;
    var realHeight = myImg.naturalHeight;
    console.log("Image width: ", realWidth);
    console.log("Image height: ", realHeight);
  }
</script>


  <img src="/my-img.jpg" id="myImage" width="250" alt="My Image">
  <button type="button" onclick="getImgSize();">Click to get Image Size</button>

Using the code above you will find the width and height of the original image in the console.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! πŸ™‚