JavaScript: Get image dimensions

171,286

Solution 1

var img = new Image();

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

  // code here to use the dimensions
}

img.src = url;

Solution 2

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

Solution 3

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%; }

Solution 4

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

Solution 5

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);
}
Share:
171,286

Related videos on Youtube

JQueeeer
Author by

JQueeeer

Updated on July 08, 2022

Comments

  • JQueeeer
    JQueeeer almost 2 years

    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?

  • Adam Casey
    Adam Casey over 11 years
    I keep getting 0 for width and height, using this exact code.
  • Adam Casey
    Adam Casey over 11 years
    It seems the image has to load, which makes sense.
  • Yaroslav Stavnichiy
    Yaroslav Stavnichiy almost 11 years
    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.
  • Shumii
    Shumii over 10 years
    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 () {};
  • JustAndrei
    JustAndrei about 9 years
    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().
  • DavidDunham
    DavidDunham over 7 years
    Why would this reusable function with deferrants be downvoted?!
  • bharatesh
    bharatesh over 7 years
    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.
  • user1702401
    user1702401 about 7 years
    That's not working, since image is not loaded yet - image loading is done asynchronously, so you have to wait for load event.
  • Ajay Gaur
    Ajay Gaur almost 7 years
    Why is onload before than setting the url of image?
  • biomorgoth
    biomorgoth almost 7 years
    @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?
  • Apolo
    Apolo over 5 years
    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
    Apolo over 5 years
    'using only JavaScript' and this is jQuery, I guess
  • krankuba
    krankuba almost 5 years
    You get upvote from me although it is using jQuerry. The approach is that matters.
  • YakovL
    YakovL over 4 years
    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
  • Kamlesh
    Kamlesh over 4 years
    img.naturalWidth and img.naturalHeight is correct answer
  • jahooma
    jahooma over 4 years
    Thank you @Kamlesh I needed the natural dimensions.
  • mark_h
    mark_h over 3 years
    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.
  • Shumii
    Shumii over 3 years
    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
  • Mehadi Hassan
    Mehadi Hassan over 3 years
    Best answer for imported image in react
  • Jeremy Trpka
    Jeremy Trpka over 3 years
    Is there a way to get the sizes outside the onload listener?
  • Shumii
    Shumii over 3 years
    You can do it anywhere you want. But it might come back as 0 if its not loaded