How to: Get Image Size (Height & Width) using JavaScript

How to: Get Image Size using JavaScript

We can use JavaScript’s built-in Image object to retrieve the dimensions of an image. The width and height properties provide the width and height of the image in pixels, respectively.

Here’s an example of how you can use the Image object to get the size of an image:

// Create a new Image object
const img = new Image();

// Set the source of the image
img.src = 'path/to/your/image.jpg';

// Wait for the image to load
img.onload = () => {
  // Get the width and height of the image
  const width = img.width;
  const height = img.height;

  // Do something with the width and height (e.g., display them on the page)
  console.log(`The image is ${width} pixels wide and ${height} pixels tall.`);
};

In this example, we first create a new Image object. Then, we set the src property of the image to the path of our image file, instructing the browser to load the image from that path.

Next, we set the onload property of the image to an arrow function that will be called once the image has finished loading. In this function, we get the width and height properties of the image, which give us the dimensions of the image in pixels.

Finally, we can use the width and height properties to perform an action, such as displaying the dimensions of the image on the page or performing another action based on the size of the image. In this example, we’re simply logging the dimensions to the console.

javascript get image height and width
As you can see, this also works just fine for remote images.

Keep in mind that the onload function will only be called once the image has finished loading. If you try to access the width and height properties of the image before it has finished loading, you’ll get undefined values. To avoid this, wait for the onload event before attempting to access the size of the image.