701

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

Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295
Saneef
  • 8,383
  • 7
  • 28
  • 42
  • 15
    It's easy with modern browsers: http://davidwalsh.name/get-image-dimensions – Yarin Jan 09 '15 at 05:08
  • Most of the answers below just get the style width and height, not the actual image's width and height. Use `imgElement.naturalWidth` and `imgElement.naturalHeight` for getting width and height. – Bamdad Dec 29 '20 at 08:09

32 Answers32

870

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

const img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';

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

Ahmed ElMetwally
  • 2,045
  • 3
  • 8
  • 14
Josh Stodola
  • 79,922
  • 46
  • 179
  • 226
460

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;
Christian C. Salvadó
  • 769,263
  • 179
  • 909
  • 832
Rex M
  • 138,842
  • 31
  • 279
  • 313
426

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

imageElement.naturalHeight

and

imageElement.naturalWidth

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

MultiplyByZer0
  • 5,209
  • 3
  • 29
  • 46
olliej
  • 34,319
  • 9
  • 56
  • 55
111

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() {
        alert($(this).height());
        alert($(this).width());
    });
});
mrtsherman
  • 38,596
  • 21
  • 85
  • 109
103

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" />

Results:

/*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

Results:

/*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.

Results:

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

/*Actual Rendered size*/    120                  150
CDspace
  • 2,611
  • 17
  • 32
  • 36
paulo62
  • 2,471
  • 1
  • 20
  • 14
  • "*which I think is now obsolete*" What do you mean? Do you mean deprecated? Or removed? And do you _know? "I think" is not very reassuring if I am going to depend on an answer. – TylerH Apr 27 '22 at 14:22
66

Using JQuery you do this:

var imgWidth = $("#imgIDWhatever").width();
Ian Suttle
  • 3,354
  • 2
  • 22
  • 27
27

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.

Thinker
  • 13,722
  • 8
  • 39
  • 52
20

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';
Lee Hesselden
  • 784
  • 5
  • 11
17

Let's combine everything we learned here into one simple function (imageDimensions()). It uses 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 a successful loading 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)
        console.info(dimensions)
    } catch(error) {
        console.error(error)
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>

Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>
Neurotransmitter
  • 5,484
  • 2
  • 47
  • 36
  • thanks for this code, but it returns 0 for width and height in firefox for SVG images without defined width and height attributes (eg, ones with only viewBox set). – Crashalot Aug 29 '20 at 08:16
  • @Crashalot right, this is not for vector images, this works only for raster ones. – Neurotransmitter Aug 30 '20 at 10:07
11

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");

  console.log({
    "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.

Saneef
  • 8,383
  • 7
  • 28
  • 42
  • 4
    Just upvote the existing answers that provide helpful content; don't copy from several of them into a new one; you're just duplicating content then. – TylerH Jun 27 '19 at 15:13
8

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']);
}
Matteo Italia
  • 119,648
  • 17
  • 200
  • 293
claudio
  • 81
  • 1
  • 1
8

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

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');
Community
  • 1
  • 1
dev101
  • 1,313
  • 2
  • 17
  • 32
8

To get the natural height and width:

document.querySelector("img").naturalHeight;
document.querySelector("img").naturalWidth;
<img src="img.png">

And if you want to get style height and width:

document.querySelector("img").offsetHeight;
document.querySelector("img").offsetWidth;
sundeep sharma
  • 293
  • 4
  • 9
7

With jQuery library-

Use .width() and .height().

More in jQuery width and jQuery heigth.

Example Code-

$(document).ready(function(){
    $("button").click(function()
    {
        alert("Width of image: " + $("#img_exmpl").width());
        alert("Height of image: " + $("#img_exmpl").height());
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg">
<button>Display dimensions of img</button>
Abrar Jahin
  • 13,156
  • 22
  • 105
  • 151
7

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 = "http://example.com/myimage.jpg";

This is correct:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";

Conclusion:

Use img, not this, in onload function.

Brian
  • 168
  • 2
  • 5
  • img.src above has a typo, should be " not : I tried to edit this but can't because: "Edits must be at least 6 characters; is there something else to improve in this post?" Otherwise a very simple solution that works perfectly! – user2677034 Apr 03 '20 at 04:51
  • Thanks @user2677034 for noticing. I didn't see that. I'll blame Apple's keyboard. Just kidding... It was probably my fault. ;P – Brian Apr 11 '20 at 16:07
6

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

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})
vusan
  • 4,921
  • 4
  • 39
  • 79
sub
  • 69
  • 1
  • 2
3

JQuery Answer:

$height = $('#image_id').height();
$width  = $('#image_id').width();
Community
  • 1
  • 1
Eli Geske
  • 65
  • 1
2

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.
    $('#testImage').remove();
}
//append to body
$('body').append(tempImg);
//Set an image url. I am using an image which I got from google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';

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

muhammed basil
  • 1,824
  • 1
  • 21
  • 39
2

This is an alternative answer for Node.js, that isn't likely what the OP meant, but could come in handy and seems to be in the scope of the question.

This is a solution with Node.js, the example uses Next.js framework but would work with any Node.js framework. It uses probe-image-size NPM package to resolve the image attributes from the server side.

Example use case: I used the below code to resolve the size of an image from an Airtable Automation script, which calls my own analyzeImage API and returns the image's props.

import {
  NextApiRequest,
  NextApiResponse,
} from 'next';
import probe from 'probe-image-size';

export const analyzeImage = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
  try {
    const result = await probe('http://www.google.com/intl/en_ALL/images/logo.gif');

    res.json(result);
  } catch (e) {
    res.json({
      error: true,
      message: process.env.NODE_ENV === 'production' ? undefined : e.message,
    });
  }
};

export default analyzeImage;

Yields:

{
"width": 276,
"height": 110,
"type": "gif",
"mime": "image/gif",
"wUnits": "px",
"hUnits": "px",
"length": 8558,
"url": "http://www.google.com/intl/en_ALL/images/logo.gif"
}
Vadorequest
  • 14,569
  • 21
  • 102
  • 201
2

My two cents in jquery

Disclaimer: This does not necessarily answer this question, but broadens our capabilities. Tested and working in jQuery 3.3.1

Lets consider:

  1. You have the image url/path and you want to get the image width and height without rendering it on the DOM,

  2. Before rendering image on the DOM, you need to set offsetParent node or image div wrapper element to image width and height, to create a fluid wrapper for different image sizes, i.e when clicking a button to view image on a modal/lightbox

This is how i will do it:

// image path
const imageUrl = '/path/to/your/image.jpg'

// Create dummy image to get real width and height
$('<img alt="" src="">').attr("src", imageUrl).on('load', function(){
    const realWidth = this.width;
    const realHeight = this.height;
    alert(`Original width: ${realWidth}, Original height: ${realHeight}`);
})
Ngatia Frankline
  • 2,461
  • 2
  • 17
  • 17
1

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()));
}
Hraban
  • 535
  • 5
  • 10
  • I never understood the use of regexp for this when using jQuery. Since jQuery will normalize the attribute for you you get away just fine by using `s.substr(4,s.length-5)`, it's at least easier on the eyes ;) – Jonas Schubert Erlandsson Jan 29 '13 at 17:32
1

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

$(document).ready(function(){
   var width = img.clientWidth;
   var height = img.clientHeight;

 });
1

Simply, you can test like this.

  <script>
  (function($) {
        $(document).ready(function() {
            console.log("ready....");
            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");
                    }
                }
            }
        });
    }(jQuery));
  </script>
cloudrain21
  • 581
  • 4
  • 16
1

Maybe this will help others. In my case, I have a File type (that is guaranteed to be an image) & I want the image dimensions without loading it on the DOM.

General strategy: Convert File to ArrayBuffer -> Convert ArrayBuffer to base64 string -> use this as the image source with an Image class -> use naturalHeight & naturalWidth to get dimensions.

const fr = new FileReader();
fr.readAsArrayBuffer(image); // image the the 'File' object
fr.onload = () => {
  const arrayBuffer: ArrayBuffer = fr.result as ArrayBuffer;

  // Convert to base64. String.fromCharCode can hit stack overflow error if you pass
  // the entire arrayBuffer in, iteration gets around this
  let binary = '';
  const bytes = new Uint8Array(arrayBuffer);
  bytes.forEach(b => binary += String.fromCharCode(b));
  const base64Data = window.btoa(binary);

  // Create image object. Note, a default width/height MUST be given to constructor (per 
  // the docs) or naturalWidth/Height will always return 0.
  const imageObj = new Image(100, 100);
  imageObj.src = `data:${image.type};base64,${base64Data}`;
  imageObj.onload = () => {
    console.log(imageObj.naturalWidth, imageObj.naturalHeight);
  }
}

This allows you to get the image dimensions & aspect ratio all from a File without rendering it. Can easily convert the onload functions to RxJS Observables using fromEvent for a better async experience:

// fr is the file reader, this is the same as fr.onload = () => { ... }
fromEvent(fr, 'load')
0

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

$('.right-sidebar').find('img').each(function(){
    $(this).removeAttr("width");
    $(this).removeAttr("height");
    $(this).imageResize();
});

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

Ram
  • 3,032
  • 10
  • 39
  • 56
Rogoit
  • 65
  • 7
0
var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

This is my method, hope this helpful. :)

DHA
  • 19
  • 2
0
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(event.target.files[0]);

 }
 return;

 }

 img.src = URL.createObjectURL(event.target.files[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!!!

Daniel Adenew
  • 7,255
  • 7
  • 54
  • 75
0

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

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
xlm
  • 5,564
  • 13
  • 48
  • 52
0

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;
      };
      reader.readAsDataURL(file);
    }
   return h, w;
}
itsCodingThing
  • 191
  • 1
  • 4
0

You can also use:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;
sth
  • 211,504
  • 50
  • 270
  • 362
praveenjayapal
  • 36,211
  • 29
  • 70
  • 72
-1
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 ...
Martin Prikryl
  • 167,268
  • 50
  • 405
  • 846
-2

Try

function sizes() {
  console.log(`width: ${pic.width}, height:${pic.height}`);
}
<img id="pic" src="https://picsum.photos/300/150">
<button onclick="sizes()">show size</button>
Kamil Kiełczewski
  • 71,169
  • 26
  • 324
  • 295