HTML5 - how to get image dimension
Asked Answered
G

1

13

I have this script, it's used to fetch the width and the height of browser uploaded image.

reference: http://renevier.net/misc/resizeimg.html

function createReader(file) {
    reader.onload = function(evt) {
        var image = new Image();
        image.onload = function(evt) {
            var width = this.width;
            var height = this.height;
            alert (width); // will produce something like 198
        };
        image.src = evt.target.result; 
    };
    reader.readAsDataURL(file);
}

for (var i = 0, length = input.files.length; i < length; i++) {
    createReader(input.files[i]);
}

I want to access the value width and height from outside the createReader function. How can I do that?

Grisgris answered 2/3, 2011 at 21:34 Comment(6)
um... have createReader return something. That's a good start.Elaineelam
the var width and height only can access inside the image.onload function, that's why I couldn't "return something"Grisgris
Can't you create the variables width and height in the scope where you want to return them, such as the createReader function?Sirenasirenic
@victor: can you explain more or give an example?Grisgris
@Victor that just won't work ...Subgenus
@runrunforest Nah, nevermind. That won't work, as Pointy pointed (hah) out.Sirenasirenic
S
30

Change "createReader" so that you pass in a handler function to be called when the image is available:

function createReader(file, whenReady) {
    reader.onload = function(evt) {
        var image = new Image();
        image.onload = function(evt) {
            var width = this.width;
            var height = this.height;
            if (whenReady) whenReady(width, height);
        };
        image.src = evt.target.result; 
    };
    reader.readAsDataURL(file);
}

Now when you call it, you can pass in a function to do whatever it is you want done with the image dimensions:

  createReader(input.files[i], function(w, h) {
    alert("Hi the width is " + w + " and the height is " + h);
  });
Subgenus answered 2/3, 2011 at 22:8 Comment(2)
fantastic answer. if i can give 10 upvotes, i would!! The whenReady really helped me because i did not know why sometimes the retrieval of the height worked and sometimes it does not. Any further explanation on when to use a whenReady type handler. And why does this reading the file using File API require it?Swanky
@kimsia well a lot of APIs like that are asynchronous - when you call them, a sequence of events is set in motion, but it doesn't all happen immediately. The "callback" mechanism lets you put in place code to be run when a long-term operation is complete. Network operations, file system interactions, and other stuff like that is asynchronous because such things involve hardware realities that aren't immediate.Subgenus

© 2022 - 2024 — McMap. All rights reserved.