How to Get Image Original Dimensions (Width & Height) using JavaScript

When you working with the image dimensions, it’s always recommended to get the real width and height of the image. The naturalWidth and naturalHeight property provide an easy way to retrieve the original dimensions of the image using JavaScript. You can easily get the original size (width and height) of the image using JavaScript.

naturalWidth
Assume that you have an image which is originally 250px wide and you make it 550px wide by CSS style or HTML “width” property. The naturalWidth will return the original width 250 although the display width is 550.

naturalHeight
Assume that you have an image which is originally 100px high and you make it 250px high by CSS style or HTML “height” property. The naturalHeight will return the original height 100 although the display height is 250.

<img src="codexworld.png" id="image" width="500px" />
// HTML DOM image
var image = document.getElementById('image');

// image original width
var originalWidth = image.naturalWidth;

// image original height
var originalHeight = image.naturalHeight;

Get Real Image Dimensions by Button Click
The following code snippet shows how you can get the original size (width and height) of the image using JavaScript.

<img src="codexworld.png" id="image" width="500px" />

<button onclick="getOriginalSize()">Get Dimensions</button>
function getOriginalSize(){  
    var image = document.getElementById('image');
    
    var originalWidth = image.naturalWidth; 
    var originalHeight = image.naturalHeight;
    
    alert("Original width=" + originalWidth + ", " + "Original height=" + originalHeight);
}

Leave a reply

keyboard_double_arrow_up