Base64 图像解码问题 - 空 .png 文件?

Base64 image decoding issue - empty .png file?

我正在尝试从基于 html 代码生成的 <canvas> 元素中获取 .png 图像。

我使用的 javascript 是:

function canvityo() {
        html2canvas(document.body, {
            onrendered: function(canvas) {
            document.body.appendChild( canvas );
            var dataURL = canvas.toDataURL();

        $.ajax({
          type: "POST",
          url: "imgprocess.php",
          data: { 
             imgBase64: dataURL
          }
        }).done(function(o) {
          console.log('saved'); 
        });
  }
});
}

我链接了 html2canvas 库,它创建了很好的 <canvas>(自从我使用 appendChild 后可以看到它们),现在我想转换那些 <canvas>photo.png 文件中,以便能够将其保存在服务器上,或者 INSERT INTO 作为 blob 保存到我的数据库 table.

var dataURL = canvas.toDataURL();

到目前为止似乎一切正常(我可以设法得到这个 url,这看起来很长)。由于看起来很奇怪,我非常确定我需要使用 base64 decoding 将其检索为 image 文件。

我的 imgprocess.php 看起来像这样:

<?php

$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);

?>

它确实输出 photo.png 文件,但文件是 empty,由于我不是很有经验,所以我一直在努力寻找这个问题的原因。

也许你们可以帮我解决这个问题?

它应该是 $img = $_POST['imgBase64']; 而不是 $img = $_POST['data'];,因为在发送 ajax post 请求时,您的数据对象的键名是 imgBase64