Get the Original Width and Height of an Image

If you use the width and height properties of the image node (vanilla Javascript) or use jQuery’s width() or height() function, you’ll get the size that you see in the browser. Getting the actual dimension (native or natural width/height) of the image is actually quite easy. Let’s see how.

Using naturalWidth and naturalHeight

The naturalWidth and naturalHeight are awesome JS properties that’ll do the job. It is supported in all browsers except Internet Explorer version 8 and below.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

var image = document.getElementById('my_image');
var width = image.naturalWidth;
var height = image.naturalHeight;

Using an Image Object

For IE8 and below or any other browser that does not support the aforementioned 2 properties, we can just load the image in our JS code and then get the width/height.

var image = new Image(); // or document.createElement('img')
var width, height;
image.onload = function() {
  width = this.width;
  height = this.height;
};
image.src = 'http://lorempixel.com/output/nature-q-c-640-480-3.jpg';

Final Demo

So, here’s a final demo that does the job.


The code checks for the support of naturalWidth, if not supported then creates an Image object and uses that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

2 thoughts on “Get the Original Width and Height of an Image”

  1. this is my js code.
    var image = document.getElementById(“Img”+randImageid);
    var width = image.naturalWidth;
    var height = image.naturalHeight;

    i got error that like.

    TypeError: image is null
    var width = image.naturalWidth;

    1. Obviously, element with id ‘img*****’ does not exist. document.getElementById(“Img”+randImageid); return element of the existing image.
      Create image first, if there are no image or check imageId.

Leave a Reply

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