0

I have been trying to return an image blob object from within these nested functions. You can see in my code that I tried the idea given in this answer, but did not help. Please read all the comments in the code to grasp the scenario. Please let me know if need more details.

function resizetoBlob(file) { //resizes given image file to blob
        var blob = "";
        var reader = new FileReader();
        reader.onload = function() {

            var tempImg = new Image();
            tempImg.src = reader.result;
            tempImg.onload = function() {

                    //resize calculation done here

                    var dUrl = canvas.toDataURL('image/jpeg',0.8);
                    blob = dataURLtoBlob(dUrl);
                    //this is the blob object I need to return
            }
        }
    reader.readAsDataURL(file);
    return blob; //obviously this does not work.
}

Here is a link to the function dataURLtoBlob.

Community
  • 1
  • 1
gurung
  • 628
  • 2
  • 11
  • 33

1 Answers1

1

As you asyncronously load the Data Url, you cannot instantly return blob, instead you could perhaps pass a function as a paramater to be executed when the Data Url has finished generating. For example:

function resizetoBlob(file,func) { //resizes given image file to blob
    var blob = "";
    var reader = new FileReader();
    reader.onload = function() {

        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function() {

                //resize calculation done here

                var dUrl = canvas.toDataURL('image/jpeg',0.8);
                blob = dataURLtoBlob(dUrl);
                func(blob); //excute function, passing "blob" as a paramater
        }
    }
reader.readAsDataURL(file);
}

And then to use this function:

resizetoBlob(FILE,function(blob){
    //do whatever you wish with the blob
    //this function will run when the blob is loaded (i.e dataUrl)
    }
);

For a better understanding, and to see good clear examples of asycronous activity, check out the "duplicate" resource.

Community
  • 1
  • 1
Matthew Spence
  • 986
  • 2
  • 9
  • 27