JavaScript - function to get real image width & height

javascript

To get the real width and height of an image using JavaScript, you can create a new Image object and set the src property to the URL of the image. You can then use the onload event to execute a function that retrieves the image’s natural width and height.

Here’s an example:

function getImageSize(imageUrl, callback) {
  var img = new Image();
  img.src = imageUrl;
  img.onload = function() {
    callback({
      width: img.naturalWidth,
      height: img.naturalHeight
    });
  };
}

In this example, we define a function called getImageSize that takes two parameters: imageUrl, which is the URL of the image to retrieve the size of, and callback, which is a function to execute once the image has loaded and its size has been determined.

Inside the function, we create a new Image object and set its src property to the URL of the image. We then set the onload event to a function that retrieves the image’s natural width and height using the naturalWidth and naturalHeight properties of the img object. We then pass an object containing the width and height properties to the callback function.

To use the getImageSize function, you can call it with the URL of the image and a function to handle the result:

getImageSize('path/to/image.jpg', function(size) {
  console.log(size.width + ' x ' + size.height);
});

In this example, we call the getImageSize function with the URL of the image and a function that logs the width and height of the image to the console. When the image has loaded and its size has been determined, the callback function is executed with an object containing the width and height properties.