Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Jamz_2010 picture Jamz_2010 · Mar 28, 2013 · Viewed 112k times · Source

Is there any way of reading the contents of a HTML Canvas as binary data?

At the moment I've got the following HTML to show an input file and the canvas below it:

<p><button id="myButton" type="button">Get Image Content</button></p>
<p>Input:<input id="fileInput" type="file"/></p>
<p>Canvas<canvas id="myCanvas" width="578" height="200"/></p>

I've then setup my input file to set the canvas correctly which works fine:

$('#fileInput').on('change', function() {
    $.each(this.files, function() {
        var image = new Image();
            image.src = window.URL.createObjectURL(this);

        image.onload = function() {
            $("canvas").drawImage({
                source: image,
                x: 50, y: 50,
                width: 100,
                fromCenter: false
            });
        };
    });
});

I now need to get the binary data (Base64 encoded) from the Canvas when the button is clicked so it'll push the data to the server...

The end result is that I need to provide the user with the ability to select a file, crop/resize it, and then click a button at which point the edited image will be uploaded to the server (I can't do server-side cropping/resizing due to server-side limitations...)

Any help would be great! Cheers

Answer

Martin Atkins picture Martin Atkins · Mar 28, 2013

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.