从 HTML5 Canvas (readAsBinaryString)获取二进制(base64)数据

有没有办法将 HTML 画布的内容读取为二进制数据?

目前,我已经得到了下面的 HTML 来显示一个输入文件和它下面的画布:

<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>

然后,我设置了我的输入文件来正确地设置画布,它工作得很好:

$('#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
});
};
});
});

我现在需要获得二进制数据(Base64编码)从画布时,按钮被点击,所以它会推数据到服务器..。

最终的结果是,我需要为用户提供选择一个文件,裁剪/调整大小的能力,然后点击一个按钮,编辑后的图像将上传到服务器(由于服务器端的限制,我不能进行服务器端裁剪/调整大小...)

任何帮助将是巨大的! 干杯

142676 次浏览

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.

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/

Short answer:

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