129

I only have a URL to an image. I need to determine the height and width of this image using only JavaScript. The image cannot be visible to the user on the page. How can I get its dimensions?

JQueeeer
  • 1,321
  • 2
  • 9
  • 5
  • 2
    http://stackoverflow.com/questions/106828/javascript-get-image-height – stecb Apr 12 '11 at 09:48
  • 1
    actually [this answer](http://stackoverflow.com/questions/106828/javascript-get-image-height/952185#952185) is the only one really correct, as you have to wait until the image is loaded. – Shadow The GPT Wizard Apr 12 '11 at 09:53

9 Answers9

229
var img = new Image();

img.onload = function(){
  var height = img.height;
  var width = img.width;

  // code here to use the dimensions
}

img.src = url;
Shumii
  • 4,529
  • 5
  • 32
  • 41
  • 1
    Unless you need to obtain the dimensions synchronously. In that case you just have to insert the image to the document (using an absolute position somewhere outside the viewport) - then the dimensions are available right after calling document.appendChild(). – JustAndrei Apr 07 '15 at 10:51
  • 1
    Why is `onload` before than setting the url of image? – Ajay Gaur Apr 21 '17 at 09:11
  • 27
    @AjayGaur because `onload` is a listener that will be called asynchronously if the image is loaded correctly. If you set the listener after setting the url, the image could load just before the code reachs setting the onload itself, resulting in the listener never being called. Using analogies, if you are serving yourself a glass with water, do you first pour the water and next you put the glass to fill it? Or do you first put the glass and then you pour the water in? – biomorgoth Apr 23 '17 at 15:41
  • 13
    img.naturalWidth and img.naturalHeight is correct answer – Kamlesh Oct 09 '19 at 05:29
  • 1
    Thank you @Kamlesh I needed the natural dimensions. – jahooma Nov 18 '19 at 09:48
  • When is the onload function actually called? There is no reference to the img outside of the code in this example. I tried calling it straight after setting the img.src but always get 0 for width and height. – mark_h Jul 24 '20 at 08:10
  • I think it invoked when u set the src. Hence why u gotta setup the handler first so it will run when the src is set – Shumii Jul 24 '20 at 08:12
  • Is there a way to get the sizes outside the onload listener? – Jeremy Trpka Aug 12 '20 at 12:24
  • You can do it anywhere you want. But it might come back as 0 if its not loaded – Shumii Aug 12 '20 at 12:33
  • Many people here are confused as to when to assign the loader function. It doesn't matter if you set the onload function before or after img.src! The onload event is ansync and will fire after all statements in the code has been run, no matter where you set it. – Pål Thingbø Aug 28 '22 at 12:02
51

Make a new Image

var img = new Image();

Set the src

img.src = your_src

Get the width and the height

//img.width
//img.height
nc3b
  • 15,562
  • 5
  • 51
  • 63
  • 23
    I keep getting 0 for width and height, using this exact code. – Adam Casey Sep 18 '12 at 01:51
  • 13
    It seems the image has to load, which makes sense. – Adam Casey Sep 18 '12 at 01:54
  • 3
    additional info - although this worked for me first time it was intermittent. I think the problem is because the image has not been downloaded. I fixed by running the code which uses the dimension in the onload event handler like so: img.onload = function () {}; – Shumii Dec 13 '13 at 14:34
  • 4
    This code works, as long as the image is in the browser cache. Once cache is invalid or deleted. It won't work. So not really reliable. – bharatesh Dec 06 '16 at 10:38
  • 3
    That's not working, since image is not loaded yet - image loading is done asynchronously, so you have to wait for load event. – user1702401 Apr 17 '17 at 05:44
  • 1
    This is a really bad answer / practice. The only way it can work is when you are using local/cached image or (maybe) one of the best internet connection in the world (not tested ;D). That means it will break in production. You should wait for the load event on the image before using img width/height. – Apolo Sep 14 '18 at 14:31
  • please correct this answer, it's better to have it look like a duplicate of Shumii's answer (although this one was posted muche earlier) than have a highly upvoted wrong/unreliable one. The `onload` handler should be used here – YakovL Aug 13 '19 at 14:26
  • Best answer for imported image in react – Mehadi Hassan Aug 08 '20 at 16:49
22

naturalWidth and naturalHeight

var img = document.createElement("img");
img.onload = function (event)
{
    console.log("natural:", img.naturalWidth, img.naturalHeight);
    console.log("width,height:", img.width, img.height);
    console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
}
img.src = "image.jpg";
document.body.appendChild(img);

// css for tests
img { width:50%;height:50%; }
Bitterblue
  • 13,162
  • 17
  • 86
  • 124
6

This uses the function and waits for it to complete.

http://jsfiddle.net/SN2t6/118/

function getMeta(url){
    var r = $.Deferred();

  $('<img/>').attr('src', url).load(function(){
     var s = {w:this.width, h:this.height};
     r.resolve(s)
  });
  return r;
}

getMeta("http://www.google.hr/images/srpr/logo3w.png").done(function(test){
    alert(test.w + ' ' + test.h);
});
DavidDunham
  • 1,245
  • 1
  • 22
  • 44
6

Combining promises & typescript typing:

/**
 * Returns image dimensions for specified URL.
 */
export const getImageDimensions = (url: string): Promise<{width: number, height: number}> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({
      width: img.width,
      height: img.height,
    });
    img.onerror = (error) => reject(error);
    img.src = url;
  });
};

Usage:

try {
  const {width, height} = await getImageDimensions(entry.NWS_IMAGE);
  console.log(`Image dimensions: ${width}px x ${height}px`);
} catch (e) {
  // Could not load image from specified URL
  console.error(e);
}
Quentin S.
  • 1,462
  • 20
  • 18
5

if you have image file from your input form. you can use like this

let images = new Image();
images.onload = () => {
 console.log("Image Size", images.width, images.height)
}
images.onerror = () => result(true);

let fileReader = new FileReader();
fileReader.onload = () => images.src = fileReader.result;
fileReader.onerror = () => result(false);
if (fileTarget) {
   fileReader.readAsDataURL(fileTarget);
}
Raka Adi Nugroho
  • 3,403
  • 1
  • 8
  • 6
1

Get image size with jQuery

function getMeta(url){
    $("<img/>",{
        load : function(){
            alert(this.width+' '+this.height);
        },
        src  : url
    });
}

Get image size with JavaScript

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

Get image size with JavaScript (modern browsers, IE9+ )

function getMeta(url){   
    var img = new Image();
    img.addEventListener("load", function(){
        alert( this.naturalWidth +' '+ this.naturalHeight );
    });
    img.src = url;
}

Use the above simply as: getMeta( "http://example.com/img.jpg" );

https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement

Sunny Kumar
  • 823
  • 6
  • 14
0

Similar question asked and answered using JQuery here:

Get width height of remote image from url

function getMeta(url){
  $("<img/>").attr("src", url).load(function(){
     s = {w:this.width, h:this.height};
     alert(s.w+' '+s.h);      
  }); 
}

getMeta("http://page.com/img.jpg");
Community
  • 1
  • 1
Luke Knepper
  • 931
  • 8
  • 18
-5

Following code add image attribute height and width to each image on the page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function addImgAttributes()
{
    for( i=0; i < document.images.length; i++)
    { 
        width = document.images[i].width;
        height = document.images[i].height;
        window.document.images[i].setAttribute("width",width);
        window.document.images[i].setAttribute("height",height);

    }
}
</script>
</head>
<body onload="addImgAttributes();">
<img src="2_01.jpg"/>
<img src="2_01.jpg"/>
</body>
</html>
Testere
  • 23
  • 1
  • 15
    The question was about getting image dimensions without showing image to the user. Setting image width and height attributes after image has been displayed makes absolutely no sense. – Yaroslav Stavnichiy May 02 '13 at 14:54