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

2022-01-17 00:00:00 javascript html html5-canvas fileapi

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

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

目前我有以下 HTML 来显示输入文件及其下方的画布:

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
            });
        };
    });
});

我现在需要在单击按钮时从画布中获取二进制数据(Base64 编码),以便将数据推送到服务器...

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

推荐答案

canvas 元素提供了一个 toDataURL 方法,该方法返回一个 data:包含给定格式的 base64 编码图像数据的 URL.例如:

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

虽然返回值不是只是 base64 编码的二进制数据,但只要去掉方案和文件类型就可以得到你想要的数据是一件简单的事情.

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.

如果浏览器认为您已将任何从不同来源加载的数据绘制到画布上,则 toDataURL 方法将失败,因此此方法仅在您的图像文件从与其脚本执行此操作的 HTML 页面相同的服务器.

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.

有关详细信息,请参阅 canvas API 上的 MDN 文档,其中包括关于 toDataURL 的详细信息,以及 关于 data: 的维基百科文章URI 方案,其中包含有关您将从该调用中收到的 URI 格式的详细信息.

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.

相关文章