在服务器端保存画布图像时,从base64数据字符串生成空白图像

when saving canvas image server-side, from a base64 data string,it produce blank image

本文关键字:图像 base64 数据 字符串 空白 保存 服务器端 布图像      更新时间:2023-09-26

我在PHP中保存画布图像有问题。我得到一个空白的.png文件。我搜索了很多关于这个问题,但找不到任何有用的东西。为什么它保存一个空白的图像,而不是渲染真实的图像?

JavaScript代码:

html2canvas([document.getElementById('dadycool')], {
  onrendered: function (canvas) {
        var data = canvas.toDataURL();
        var image = new Image();
        image.src = data;
        document.getElementById('imagec').appendChild(image);
        console.log(data);
        $.ajax({
  type: "POST",
  url: "up.php",
  data: { 
     imgBase64: data
  }
}).done(function(o) {
  console.log('saved'); 
}); 
}   
PHP代码:
<?php
// requires php5
define('localhost/samp/sample2/uploads', 'images/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = localhost/samp/sample2/uploads . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

我怀疑您没有配置您的开发框来显示PHP错误消息。您正在定义一个不是有效标识符的常量:

define('localhost/samp/sample2/uploads', 'images/');

这意味着你不能直接使用它:

$file = localhost/samp/sample2/uploads . uniqid() . '.png';

…应该触发:

Notice: Use of undefined constant localhost - assumed 'localhost'
Notice: Use of undefined constant samp - assumed 'samp'
Warning: Division by zero
Notice: Use of undefined constant sample2
Warning: Division by zero
Notice: Use of undefined constant uploads - assumed 'uploads'
Warning: Division by zero

file将只包含基文件名(例如53676a01cdb59.png),而不包含路径组件。您需要使用以下语法:

$file = constant('localhost/samp/sample2/uploads') . uniqid() . '.png';

…或者,更好的是,给常量起一个合理的名字:

define('DIR_UPLOADS', 'images/');

我有同样的问题-它看起来像base64数据被正确发送,但总是无法生成图像服务器端。我发现的解决方案是使用'FormData'对象和一个非常简单的xhr请求发布到服务器。

var url='/path/to/save.php';
var data=oCanvas.toDataURL('image/png').replace(/^data:image'/(png|jpg);base64,/, '');
var fd=new FormData();
fd.append('imgdata',data);
var request = new XMLHttpRequest();
request.open('POST', url);
request.send(fd);

我99%肯定这个问题是由xhr请求发送的不正确的Content-Type报头引起的。将基本的xhr请求与FormData结合使用,将强制xhr请求与具有正确定义内容边界的multipart/FormData内容类型一起发送。