0

I've got a problem with getting image dimensions. I want to know the width and height of image without its loading into document. At present I have code as follows:

 function getImageSize (path) {
  var image = new Image();
  image.name = path;
  var d = image.onload = function() {
   var w = this.width;
   var h = this.height;
   return {width : w, height : h};
  }();
  image.src = path;
  return d;
 }

If I call that function, I get object containing undefined in both index (w, h). I've tried not call onload handler by exclude parenthesis (8 line) but what I get is function code.

Note that if I call alert(w) inside onload handler body, I can see width of picture but outside it not.

Does someone know how to solve that problem? How can I get image dimension?

Mattios550
  • 372
  • 1
  • 5
  • 18

2 Answers2

6

This block

var d = image.onload = function() {
   var w = this.width;
   var h = this.height;
   return {width : w, height : h};
}();

looks very fishy. This is actually executing the function immediately and assigning the object {width : w, height : h} to image.onload and d. w and h will contain the width and height of the window because this will refer to window.

You have to assign the function to image.onload, not execute it. The reason you have to assign the function is that it takes time to load the image and the callback gets called once the image was loaded. The whole process is asynchronous. That also means that you cannot return the dimensions of the image from getImageSize. You have to make it accept a callback, which you have to call in the load callback.

For example:

function getImageSize (path, callback) {
  var image = new Image();
  image.name = path;
  image.onload = function() {
   callback({width : this.width, height : this.height};
  }
  image.src = path;
};

and call the function with

getImageSize('path/to/image', function(dim) {
    // do something with dim.width, dim.height
});

Have a look at the first part of my answer here to learn about the difference of synchronous and asynchronous code, and the role of callbacks.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • As I said, you cannot return the dimensions. Quoting myself: *"That also means that you **cannot** return the dimensions of the image from `getImageSize`"*. All code that needs access to the dimensions has to go or be called from the callback. – Felix Kling Mar 17 '13 at 12:42
0

onload is an asynchronous call and cannot return anything useful out of the calling function.

You will have to use a global variable and timer check to wait for the function to complete and then access the values.

ATOzTOA
  • 34,814
  • 22
  • 96
  • 117