[javascript] 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/

This question is related to javascript image height width

The answer is


ES6: Using async/await you can do below getMeta function in sequence-like way and you can use it as follows (which is almost identical to code in your question (I add await keyword and change variable end to img, and change var to let keyword). You need to run getMeta by await only from async function (run).

_x000D_
_x000D_
function getMeta(url) {
    return new Promise((resolve, reject) => {
        let img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject();
        img.src = url;
    });
}

async function run() {

  let img = await getMeta("http://shijitht.files.wordpress.com/2010/08/github.png");

  let w = img.width;
  let h = img.height; 

  size.innerText = `width=${w}px, height=${h}px`;
  size.appendChild(img);
}

run();
_x000D_
<div id="size" />
_x000D_
_x000D_
_x000D_


Just pass a callback as argument like this:

_x000D_
_x000D_
function getMeta(url, callback) {_x000D_
    var img = new Image();_x000D_
    img.src = url;_x000D_
    img.onload = function() { callback(this.width, this.height); }_x000D_
}_x000D_
getMeta(_x000D_
  "http://snook.ca/files/mootools_83_snookca.png",_x000D_
  function(width, height) { alert(width + 'px ' + height + 'px') }_x000D_
);
_x000D_
_x000D_
_x000D_


The w and h variables in img.onload function are not in the same scope with those in the getMeta() function. One way to do it, is as follows:

Fiddle: http://jsfiddle.net/ppanagi/28UES/2/

function getMeta(varA, varB) {
    if (typeof varB !== 'undefined') {
       alert(varA + ' width ' + varB + ' height');
    } else {
       var img = new Image();
       img.src = varA;
       img.onload = getMeta(this.width, this.height);
    }
}


getMeta("http://snook.ca/files/mootools_83_snookca.png");

Get image size with jQuery
(depending on which formatting method is more suitable for your preferences):

function getMeta(url){
    $('<img/>',{
        src: url,
        on: {
            load: (e) => {
                console.log('image size:', $(e.target).width(), $(e.target).height());
            },
        }
    });
}

or

function getMeta(url){
    $('<img/>',{
        src: url,
    }).on({
        load: (e) => {
            console.log('image size:', $(e.target).width(), $(e.target).height());
        },
    });
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to height

How to Determine the Screen Height and Width in Flutter How do I change UIView Size? Adjust UILabel height to text iFrame Height Auto (CSS) CSS height 100% percent not working What is the height of Navigation Bar in iOS 7? Relative div height How to fill 100% of remaining height? CSS div 100% height Change UITableView height dynamically

Examples related to width

How to Determine the Screen Height and Width in Flutter Change New Google Recaptcha (v2) Width How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest Full width image with fixed height Width equal to content CSS to make table 100% of max-width CSS Input with width: 100% goes outside parent's bound HTML email in outlook table width issue - content is wider than the specified table width How to set up fixed width for <td>? How to make div's percentage width relative to parent div and not viewport