Search code examples
javascriptimageheightwidth

Get width height of remote image from url


So the alert gives undefined values for the width and height. I think the w and h values of the image from the img.onload calculation is not being passed to the values to return, or it may be returning w and h before the onload calculates them:

function getMeta(url){
 var w; var h;
 var img=new Image;
 img.src=url;
 img.onload=function(){w=this.width; h=this.height;};
 return {w:w,h:h}    
}

// "http://snook.ca/files/mootools_83_snookca.png" //1024x678
// "http://shijitht.files.wordpress.com/2010/08/github.png" //128x128

var end = getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");
var w = end.w;
var h = end.h;
alert(w+'width'+h+'height');

How can I have the alert show the correct width and height?

http://jsfiddle.net/YtqXk/


Solution

  • Get image size with JavaScript

    In order to read the data from an image you'll need to make sure it's first loaded. Here's a callback-based approach and two promise-based solutions:

    Callback

    const getMeta = (url, cb) => {
      const img = new Image();
      img.onload = () => cb(null, img);
      img.onerror = (err) => cb(err);
      img.src = url;
    };
    
    // Use like:
    getMeta("https://i.sstatic.net/qCWYU.jpg", (err, img) => {
      console.log(img.naturalWidth, img.naturalHeight);
    });

    Using the load Event listener (Promise):

    const getMeta = (url) =>
      new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = (err) => reject(err);
        img.src = url;
      });
    
    // Usage example: 
    ;(async() => {
      const img = await getMeta('https://i.sstatic.net/qCWYU.jpg');
      console.dir(img.naturalHeight + ' ' + img.naturalWidth);
    })();

    Using HTMLImageElement.decode() (Promise)

    const getMeta = async (url) => {
      const img = new Image();
      img.src = url;
      await img.decode();  
      return img
    };
    
    // Usage example:
    getMeta('https://i.sstatic.net/qCWYU.jpg').then(img => {
      console.dir(img.naturalHeight +' '+ img.naturalWidth);
    });