3

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.

1 Answer 1

2

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);
            }
        })();
    };
Sign up to request clarification or add additional context in comments.

1 Comment

That's pretty much how I do it also. I've played around with using createimagedata and looping through a typedarray but the image comes out garbled. It's a shame because this would be perfect for this particular application within a webworker. It would allow being able to send huge images to the worker without having to clone it. Thanks anyway. I'll mark the question as answered as soon as I am able.

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.