How To Get Real Width And Height Of Image Using JavaScript

By bhagwatchouhan
How To Get Real Width And Height Of Image Using JavaScript

This tutorial provides the steps required to get the actual width and height of an Image using JavaScript. The visible width and height may be different as compared to the actual width and height.

Image Width and Height

In several cases, we might be required to find out the actual width and height of the image to set the parent width and height. We can get the width and height of the given image the naturalWidth and naturalHeight properties as shown below.

// Get the Image
var image = document.querySelector( "#banner" );

// Actual/Real Width
var imgWidth = image.naturalWidth;

// Actual/Real Height
var imgHeight = image.naturalHeight;

This is the easiest way to get the real width and height of the given image.

Complete Example

This section shows a complete example to show the image width and height using an alert box.

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Actual Width and Height of Image - JavaScript</title>
<script>
window.onload = function() {

initPage();
};

function initPage() {

var button = document.querySelector( "#btn-show" );

button.addEventListener( 'click', function( event ) {

showImageDimensions();
});
}

function showImageDimensions() {

// Get the Image
var image = document.querySelector( "#banner" );

// Actual/Real Width
var imgWidth = image.naturalWidth;

// Actual/Real Height
var imgHeight = image.naturalHeight;

alert( "Actual Width=" + imgWidth + ", " + "Actual Height=" + imgHeight );
}
</script>
</head>
<body>
<h1>Image Width & Height Demo</h1>
<div>
<img id="banner" src="banner.jpg" width="350px" alt="Banner" />
</div>
<div>
<button id="btn-show" type="button">Show</button>
</div>
</body>
</html>

Remote Image

We can also get the width and height of remote images as shown below.

var remoteImageUrl = "image url";

var remoteImage = new Image();

remoteImage.onload = function() {

alert( this.width + ' ' + this.height );
};

remoteImage.src = remoteImageUrl;

We can also use the below-mentioned code on modern browsers.

var remoteImageUrl = "image url";

var remoteImage = new Image();

remoteImage.addEventListener( "load", function() {

alert( this.naturalWidth + ' ' + this.naturalHeight );
};

remoteImage.src = remoteImageUrl;

Summary

This tutorial provided the steps required to obtain the actual width and height of an Image using JavaScript.

share on :

Profile picture for user bhagwatchouhan
bhagwatchouhan