How to get image size (height & width) using JavaScript?

Are there any jQuery or pure JS APIs or methods to get the dimensions of an image on the page?

You can programmatically get the image and check the dimensions using Javascript...

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
img.src = '';

This can be useful if the image is not a part of the markup.

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

Also (in addition to Rex and Ian's answers) there is:




These provide the height and width of the image file itself (rather than just the image element).

If you are using jQuery and you are requesting image sizes you have to wait until they load or you will only get zeroes.

$(document).ready(function() {
    $("img").load(function() {

I think an update to these answers is useful because one of the best-voted replies suggests using clientWidth and clientHeight, which I think is now obsolete.

I have done some experiments with HTML5, to see which values actually get returned.

First of all, I used a program called Dash to get an overview of the image API. It states that height and width are the rendered height/width of the image and that naturalHeight and naturalWidth are the intrinsic height/width of the image (and are HTML5 only).

I used an image of a beautiful butterfly, from a file with height 300 and width 400. And this Javascript:

var img = document.getElementById("img1");

console.log(img.height,           img.width);
console.log(img.naturalHeight,    img.naturalWidth);
console.log($("#img1").height(),  $("#img1").width());

Then I used this HTML, with inline CSS for the height and width.

<img style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />


/*Image Element*/ height == 300         width == 400
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

I then changed the HTML to the following:

<img height="90" width="115" id="img1" src="img/Butterfly.jpg" />

i.e. using height and width attributes rather than inline styles


/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() ==  90       width() == 115

/*Actual Rendered size*/     90                  115

I then changed the HTML to the following:

<img height="90" width="115" style="height:120px;width:150px;" id="img1" src="img/Butterfly.jpg" />

i.e. using both attributes and CSS, to see which takes precedence.


/*Image Element*/ height ==  90         width == 115
           naturalHeight == 300  naturalWidth == 400
/*Jquery*/      height() == 120       width() == 150

/*Actual Rendered size*/    120                  150

Using JQuery you do this:

var imgWidth = $("#imgIDWhatever").width();

The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
    return function()
        return delegateMethod.apply(contextObject, arguments);

function imgTesting_onload()
    alert(this.width + " by " + this.height);

imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';

With jQuery library-

Use .width() and .height().

More in jQuery width and jQuery heigth.

Example Code-

        alert("Width of image: " + $("#img_exmpl").width());
        alert("Height of image: " + $("#img_exmpl").height());
<script src=""></script>

<img id="img_exmpl" src="">
<button>Display dimensions of img</button>

ok guys, i think i improved the source code to be able to let the image load before trying to find out its properties, otherwise it will display '0 * 0', because the next statement would have been called before the file was loaded into the browser. Requires jquery...

function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    alert (p[0]['width']+" "+p[0]['height']);

Before using real image size you should load source image. If you use JQuery framework you can get real image size in simple way.

  console.log($(this).width() + "x" + $(this).height())

Assuming, we want to get image dimensions of <img id="an-img" src"...">

// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById("an-img");

    "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
    "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
    "offsetWidth": el.offsetWidth,
    "offsetHeight": el.offsetHeight

Natural Dimensions

el.naturalWidth and el.naturalHeight will get us the natural dimensions, the dimensions of the image file.

Layout Dimensions

el.offsetWidth and el.offsetHeight will get us the dimensions at which the element is rendered on the document.

This answer was exactly what I was looking for (in jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

JQuery Answer:

$height = $('#image_id').height();
$width  = $('#image_id').width();

You can have a simple function like the following (imageDimensions()) if you don't fear using promises.

// helper to get dimensions of an image
const imageDimensions = file => new Promise((resolve, reject) => {
    const img = new Image()

    // the following handler will fire after the successful parsing of the image
    img.onload = () => {
        const { naturalWidth: width, naturalHeight: height } = img
        resolve({ width, height })

    // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
    img.onerror = () => {
        reject('There was some problem with the image.')
    img.src = URL.createObjectURL(file)

// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
    const [file] = files
    try {
        const dimensions = await imageDimensions(file)
    } catch(error) {
<script src=""></script>

Select an image:
<br />
<small>It works offline.</small>

Recently I had same issue for an error in the flex slider. The first image's height was set smaller due to the loading delay. I tried the following method for resolving that issue and it's worked.

// create image with a reference id. Id shall be used for removing it from the dom later.
var tempImg = $('<img id="testImage" />');
//If you want to get the height with respect to any specific width you set.
//I used window width here.
tempImg.css('width', window.innerWidth);  
tempImg[0].onload = function () {
    $(this).css('height', 'auto').css('display', 'none');
    var imgHeight = $(this).height();
    // Remove it if you don't want this image anymore.
//append to body
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='';

This will give you the height with respect to the width you set rather than original width or Zero.

You can also use:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

Nicky De Maeyer asked after a background picture; I simply get it from the css and replace the "url()":

var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
  console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));

You can apply the onload handler property when the page loads in js or jquery like this:-

   var width = img.clientWidth;
   var height = img.clientHeight;


Simply, you can test like this.

  (function($) {
        $(document).ready(function() {
            var i = 0;
            var img;
            for(i=1; i<13; i++) {
                img = new Image();
                img.src = 'img/' + i + '.jpg';
                console.log("name : " + img.src);
                img.onload = function() {
                    if(this.height > this.width) {
                        console.log(this.src + " : portrait");
                    else if(this.width > this.height) {
                        console.log(this.src + " : landscape");
                    else {
                        console.log(this.src + " : square");

var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser  360 browser ...

it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use


This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.

var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
    return img;
var x = myFunction('');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;

This is my method, hope this helpful. :)

function outmeInside() {
var output = document.getElementById('preview_product_image');

 if (this.height < 600 || this.width < 600) {
     output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
     alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
 } else {
     output.src = URL.createObjectURL([0]);



 img.src = URL.createObjectURL([0]);

this work for multiple image preview and upload . if you have to select for each of the images one by one . Then copy and past into all the preview image function and validate!!!

Before acquire element's attributes,the document page should be onload:


Thought this might be helpful to some who are using Javascript and/or Typescript in 2019.

I found the following, as some have suggested, to be incorrect:

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
img.src = "";

This is correct:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
img.src = ";


Use img, not this, after onload.

There is a decent solution for this problem in GeeksForGeeks. You can see the working example from the snippet below:

function CheckImageSize() {
    var image = document.getElementById("Image").files[0];
    createReader(image, function(w, h) {

        alert("Width is: " + w +
            "pixels, Height is: " + h + "pixels");

function createReader(file, whenReady) {
    var reader = new FileReader;
    reader.onload = function(evt) {
        var image = new Image();
        image.onload = function(evt) {
            var width = this.width;
            var height = this.height;
            if (whenReady) whenReady(width, height);
        image.src =;
body {
text-align: center;
<!DOCTYPE html> 
    <input type="file" id="Image" /> 
    <input type="button" value="Find the dimensions" onclick="CheckImageSize()"/> 

just pass the img file object which is obtained by the input element when we select the correct file it will give the netural height and width of image

function getNeturalHeightWidth(file) {
     let h, w;
     let reader = new FileReader();
      reader.onload = () => {
        let tmpImgNode = document.createElement("img");
        tmpImgNode.onload = function() {
          h = this.naturalHeight;
          w = this.naturalWidth;
        tmpImgNode.src = reader.result;
   return h, w;


function sizes() {
  document.body.innerHTML+= `<br> width: ${pic.width}, height:${pic.height}`
<img id="pic" src="">
<button onclick="sizes()">show size</button>