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

Is there a way to read HTML Canvas content as binary data?

At the moment, I have the following HTML to show the 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> 

Then I installed 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 }); }; }); }); 

Now I need to get the binary data (Base64 encoded) from Canvas when the button is pressed so that it moves the data to the server ...

The end result is that I need to give the user the ability to select a file, crop / resize it, and then click the button, after which the edited image will be uploaded to the server (I cannot do server cropping / resizing due to server-side restrictions ...)

Any help would be great! Greetings

+48
javascript html5 html5-canvas fileapi
Mar 28 '13 at 15:22
source share
2 answers

The canvas provides the toDataURL method, which returns the data: URL, which includes base64 encoded image data in the specified format. For example:

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

Although the return value is not only base64 encoded binary data, the easier it is to trim the schema and file type to get the data you need.

The toDataURL method will fail if the browser thinks that you have drawn on the canvas any data downloaded from another source, so this approach will work only if your image files are downloaded from the same server as the HTML page whose script performs this operation.

For more information, see the MDN documents in the canvas API , which contains information about toDataURL and the Wikipedia article on the data: URI scheme , which contains detailed information about the URI format that you will receive from this call.

+89
Mar 28 '13 at 15:30
source share

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you are using jQuery Canvas ( jCanvas ) Caleb Evans. I really use this plugin and it has an easy way to get a canvas base64 image string using $('canvas').getCanvasImage();

Here's the fiddle for you: http://jsfiddle.net/e6nqzxpn/

0
Dec 03 '15 at 20:38
source share



All Articles