[javascript] Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

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

This question is related to javascript html html5-canvas fileapi

The answer is


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.


Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to html5-canvas

Scaling an image to fit on canvas Tainted canvases may not be exported How to fix getImageData() error The canvas has been tainted by cross-origin data? JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images Resize image with javascript canvas (smoothly) How to show a running progress bar while page is loading HTML5 Canvas Resize (Downscale) Image High Quality? HTML5 Canvas Rotate Image Real mouse position in canvas Changing three.js background to transparent or other color

Examples related to fileapi

How do I download a file with Angular2 or greater Getting byte array through input type = file Convert base64 png data to javascript file objects Getting binary (base64) data from HTML5 Canvas (readAsBinaryString) How to get a file or blob from an object URL?