Categories
JavaScript Answers

How to get width height of remote image from URL with JavaScript?

Spread the love

Sometimes, we want to get width height of remote image from URL with JavaScript.

In this article, we’ll look at how to get width height of remote image from URL with JavaScript.

How to get width height of remote image from URL with JavaScript?

To get width height of remote image from URL with JavaScript, we can use the naturalWidth and naturalHeight properties.

For instance, we write

const img = new Image();
img.addEventListener("load", () => {
  console.log(img.naturalWidth, img.naturalHeight);
});
img.src = url;

to create an img element with the Image constructor.

Then we add an event listener for the load event with addEventListener.

In it, we get the width and height of the image with naturalWidth and naturalHeight.

Then we set img.src to url to load the image and run the load event handler.

Conclusion

To get width height of remote image from URL with JavaScript, we can use the naturalWidth and naturalHeight properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *