How to check a selected image’s width and height with JavaScript?

Estimated read time 1 min read

You can use the following code to check the width and height of a selected image in JavaScript:

var image = new Image();
image.src = "path/to/image.jpg";

image.onload = function() {
  var width = image.width;
  var height = image.height;
  console.log("Image width: " + width + "px");
  console.log("Image height: " + height + "px");

In this code, we create a new instance of the Image object and set its src property to the path of the image. Then, we use the onload event of the image to run a function that logs the width and height of the image to the console. The width and height properties of the Image object contain the dimensions of the image in pixels.

It’s important to note that the onload event will only fire after the image has finished loading, so it’s necessary to use this event to access the dimensions of the image. If you try to access the width and height properties before the image has finished loading, they will be undefined.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply