How to get image dimensions in JavaScript without adding image to DOM

I’m trying to find out how to determine the width and height of an image using JavaScript, even though the image isn’t visible on the webpage. I only have the URL or path to the image file.

I’ve tried several methods but haven’t had any success yet. Here’s an example of what I attempted:

var picture = $('<img>').attr('src', 'assets/banner.jpg');
console.log($(picture).height());

This code simply returns 0 instead of the correct dimensions. The image is accessible at that path and displays correctly when I use it on the page. Is there a way to obtain the actual width and height values of an image without loading it into the DOM? I’m currently using jQuery but I’m also open to using plain JavaScript solutions.

The problem is that image loading happens asynchronously - your console.log runs right away while the image’s still downloading. I hit this same issue building a photo gallery where I needed dimensions for layout.

The trick is waiting for the complete load cycle. Here’s what actually works:

const img = new Image();
img.addEventListener('load', function() {
    console.log('Width:', img.width, 'Height:', img.height);
    // Your processing code here
});
img.src = 'assets/banner.jpg';

This creates an Image object in memory without touching the DOM. The load event fires once the browser’s fully processed the image data and calculated dimensions. If you’re using jQuery, wrap this in a function that returns dimensions to a callback. Just remember - any code that needs these dimensions has to run inside the load handler or after it’s done.

You’re accessing the dimensions before the image loads. When you create an image element and set its source, the browser needs time to fetch and decode the data before width and height are available. I hit this same issue on a project where I needed to validate upload dimensions. You need to wait for the load event:

function getImageDimensions(imagePath) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      resolve({
        width: this.naturalWidth,
        height: this.naturalHeight
      });
    };
    img.onerror = reject;
    img.src = imagePath;
  });
}

getImageDimensions('assets/banner.jpg').then(dimensions => {
  console.log(dimensions.width, dimensions.height);
});

Use naturalWidth and naturalHeight - they give you actual image dimensions regardless of CSS styling. The Promise approach handles both success and error cases cleanly.

you gotta let the img load 1st! use the onload event like this: var img = new Image(); img.onload = function() { console.log(this.width, this.height); }; img.src = 'your-image.jpg'; this way it’ll show correct dimensions.