You can use the .naturalWidth and .naturalHeight properties of the image element to get its original size (width and height) in pixels. For example:

var img = document.getElementById("myImg");
var width = img.naturalWidth;
var height = img.naturalHeight;
console.log("Width: " + width + ", Height: " + height);

You can also use the .width and .height properties of the image element to get its current size (width and height) in pixels. For example:

var img = document.getElementById("myImg");
var width = img.width;
var height = img.height;
console.log("Width: " + width + ", Height: " + height);

Please be aware that if the image is not loaded yet, the values of width and height will be 0 and the naturalWidth and naturalHeight properties will be undefined or null, so it’s recommended to wait until the image is loaded before trying to get its size.

img.onload = function(){
  var width = img.naturalWidth;
  var height = img.naturalHeight;
  console.log("Width: " + width + ", Height: " + height);
}

Also, if you want to get the size of an image before it’s loaded, you can use Image() constructor and get the size of image.

var img = new Image();
img.src = "image.jpg";
console.log("Width: " + img.width + ", Height: " + img.height);

This will give you the size of the image.

Also Read:

Categorized in: