0

i want to return imageSize but it is returning undefined. i am confused i have tried many things. in the alert i am getting size.

getImageSize : function(file) {
        var reader = new FileReader();
        var image  = new Image();
        var imageSize;
        reader.readAsDataURL(file);  
        reader.onload = function(_file) {
            image.src    = _file.target.result;
            image.onload = function() {
                imageSize = ~~(file.size/1024) +'KB';
                alert(imageSize);
            };     
        };
        return imageSize;
    }
3
  • you cann't return image size as the read method is async Commented Nov 20, 2013 at 6:29
  • This is because imageSize is still undefined by the time the return line is reached. The value of imageSize is updated only when the two onload events are fired. Commented Nov 20, 2013 at 6:31
  • is there any way to re-write this function so that i can return imageSize? Commented Nov 20, 2013 at 6:33

1 Answer 1

1

Since you are loading the image asynchronously, you cannot return the size directly. The best you can do is pass in a call-back function to be called when the size is available:

getImageSize : function(file, callback) {
    var reader = new FileReader();
    var image  = new Image();
    var imageSize;
    reader.readAsDataURL(file);  
    reader.onload = function(_file) {
        image.src    = _file.target.result;
        image.onload = function() {
            imageSize = ~~(file.size/1024) +'KB';
            callback(imageSize);
        };     
    };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.