Write a JavaScript Program to Get the Dimensions of an Image

In web development, it’s often necessary to retrieve the dimensions of an image.

This information can be used for various purposes, such as determining the appropriate size for displaying the image on a webpage or validating that the image meets certain size requirements.

In this tutorial, we’ll explore how to get the dimensions of an image using JavaScript.

To get the dimensions of an image, we first need to load the image into our JavaScript code. We can do this by creating a new Image object and setting its src attribute to the URL of the image we want to retrieve the dimensions for:

const img = new Image();
img.src = 'https://example.com/image.jpg';

Once we’ve loaded the image, we can use the naturalWidth and naturalHeight properties to retrieve its dimensions:

console.log('Image dimensions:', img.naturalWidth, 'x', img.naturalHeight);

The naturalWidth and naturalHeight properties return the intrinsic dimensions of the image, which are the dimensions of the image file itself. These properties are only available after the image has been loaded, so it’s important to wait for the load event to fire before attempting to retrieve them:

const img = new Image();
img.src = 'https://example.com/image.jpg';
img.addEventListener('load', () => {
console.log('Image dimensions:', img.naturalWidth, 'x', img.naturalHeight);
});

In this example, we’re using the addEventListener method to attach a load event handler to the image.

This handler will be called once the image has finished loading, at which point we can safely retrieve its dimensions.

It’s worth noting that if the image fails to load for any reason, the naturalWidth and naturalHeight properties will both be set to 0.

Therefore, it’s important to handle any errors that may occur during the image loading process.

In conclusion, getting the dimensions of an image in JavaScript is a simple process.

By creating a new Image object, setting its src attribute to the URL of the image, and waiting for the load event to fire, we can retrieve the intrinsic dimensions of the image using the naturalWidth and naturalHeight properties.