我在用 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/