I'm looking for a way to draw an image to a canvas directly from the html5 FileReader api.
The usual method is to create a new image object, wait for onload and then draw it to the canvas with drawImage().
However for a specific case which I do not need to go into I would like to bypass the loading of the image data completely if at all possible.
Since the filereader api supports readAsArrayBuffer() I was wondering if there is any way I could take this arraybuffer and convert it into canvas imageData in order to use ctx.putImageData(array) to render the image.
Thanks in advance.
Loading the image is a neccessary step I think; at one end of the process you just have a binary blob which could be a JPEG or PNG (or BMP, any other mime type), while at the other you have an array containing raw pixel data. While you could technically code this conversion yourself, the fileReader.readAsDataURL and ctx.drawImage methods do this for you internally.
FWIW, his is how I draw an image to canvas.
// read binary data from file object
var fileRead = function(file){
var reader = new FileReader();
reader.onload = fileReadComplete;
reader.readAsDataURL(file);
};
// convert binary data to image object
var fileReadComplete = function(e){
var img = new Image();
img.src = e.target.result;
(function(){
if (img.complete){
ctx.drawImage(img);
}
else {
setTimeout(arguments.callee, 50);
}
})();
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With