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

标签 javascript php html ajax canvas

我在用 PHP 保存 Canvas 图像时遇到问题。我得到一个空白的 .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/');

关于javascript - 在服务器端保存 Canvas 图像时,从 base64 数据字符串生成空白图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23452348/

相关文章:

javascript - HTML - 如何使这些 div 保持在一行?

javascript - 固定水平 slider 间距的简单方法

javascript - 设置 SharePoint Angular 人员选取器指令的值

php - Apache 使用过多的 CPU

php - Mysql触发器从一个表到另一个

php - Wordpress/PHP/MySql 排序结果

Javascript点击按钮,反函数

javascript - jQuery AJAX - 将额外的键/值对推送到序列化的 $_POST 数组中

javascript - 在 React 组件中动态设置 props

javascript - 如何在React中获取单击的动态添加组件的索引并将其删除?