Converting image to binary array (blob) with HTML5

Kevin picture Kevin · Jun 1, 2011 · Viewed 28.4k times · Source

I am trying to use the 'FileReader' and 'File' APIs that are supported in HTML5 in Chrome and Firefox to convert an image to a binary array, but it does not seem to be working correctly on Chrome. I just have a simple HTML page with a file as the input type:

<input id="image_upload" type="file" />

And from here I am using jQuery to grab the contents of the image and then using the API: File.getAsBinary() to convert it to a binary array. This works perfectly on Firefox but not on Chrome:

$('#image_upload').change(function() {
    var fileList = this.files;
    var file = fileList[0];
    var data =  file.getAsBinary();
            //do something with binary
});

When this method executes on Chrome I get an error in the console saying:

uncaught TypeError: Object #<File> has no method 'getAsBinary'

I am using the most up-to-date version of Google Chrome which as of today (2011-05-31) is version: 11.0.696.71 and according to sources this method is supposed to be supported with the most current version of Chrome.

That did not seem to work so I tried to use the FileReader API and did not have any luck with that either. I tried doing this to no avail:

$('#image_upload').change(function() {
    var fileList = this.files;
    var file = fileList[0];
    var r = new FileReader();
    r.readAsBinaryString(file);
    alert(r.result);
]);

But that only returns nothing which I assume is because readAsBinaryString() is a void method. I am at a complete loss of how to get this working for both Chrome and Firefox. I have searched all over the web looking at countless examples to no avail. How can I get it working?

Answer

Ilmari Heikkinen picture Ilmari Heikkinen · Jun 1, 2011

The FileReader API is an asynchronous API, so you need to do something like this instead:

var r = new FileReader();
r.onload = function(){ alert(r.result); };
r.readAsBinaryString(file);