将画布解码为 dataURL

2021-12-21 00:00:00 canvas php javascript

我在使用使用 canvas 的 todataurl() 方法创建的数据时遇到困难.目前,我的代码将结果数据发送到我的 php 服务器,该服务器使用 file_put_contents() 方法创建一个文件来存储该数据.现在,如果我将文件中产生的乱码剪切并粘贴到图像标签 src 中,它可以正常工作并正确显示,因此我认为到目前为止一切都很好.

I'm having difficulty using data created with canvas's todataurl() method. Currently my code sends the resulting data to my php server which uses the file_put_contents() method to create a file to store that data. Now if I cut and paste the resulting gibberish from the file into an image tag src it works fine and displays properly so I assume so far everything is peachy.

但是当我尝试在 JS 中使用代码时,我一直遇到问题.我试过 php 的 base64_decode 方法,但一直收到损坏的文件.我找到了这个代码:

But I keep running into issues when I try to use the code in JS. I've tried php's base64_decode method but kept getting currupt files. I found this code:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);

并且仍然有损坏的文件.理想情况下,我想用它创建一个 .png 文件,但我只想在 JS 中再次处理数据文件.非常感谢任何帮助.

and still got currupted files. Ideally I'd like to create a .png file with it but I'd settle for just processing the data file again in JS. Any help greatly appreciated.

推荐答案

看来您必须通过 toDataURL() 函数删除预先添加到图像数据的标题.在客户端,您可以像这样去除标题:

It seems you have to get rid of the header that is prepended to the image data by the toDataURL() function. On the client side you can strip off the header like this:

..
var data=canvas.toDataURL();
var output=data.replace(/^data:image/(png|jpg);base64,/, "");
// now send "output" to the server
..

在服务器端使用这个:

<?php
    $decocedData = base64_decode($encodedData);
?>

相关文章