ChatGPT解决这个技术问题 Extra ChatGPT

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


M
Martin Atkins

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.


Not every web browser canvas.toDataURL() comes in PNG default; you have to specify it though canvas.toDataURL('image/png')
M
Masih Jahangiri

Short answer:

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

Completed forgot you had to split the ;base64, value. Drove me crazy for 45 mins
H
Hans Tiono

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/


canvas.getCanvasImage is not a function
@RajivSharma actually jCanvas does have that function projects.calebevans.me/jcanvas/docs/getCanvasImage the canvas.toDataURL(); however does seem easier.