【问题标题】:when saving canvas image server-side, from a base64 data string,it produce blank image从base64数据字符串保存画布图像服务器端时,它会产生空白图像
【发布时间】:2023-03-26 16:43:01
【问题描述】:

我在 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.';
?>

【问题讨论】:

  • 默认情况下,据我所知,toDataUrl返回png图片,$img = str_replace('data:image/jpg;base64,', '', $img);应该是$img = str_replace('data:image/png;base64,', '', $img);
  • 是的!我忘了写我的代码的更新版本 :D 但我的问题仍然存在。
  • 您可以将PHP部分替换为PHP-FileUpload及其DataUriUpload组件,如documented here。它也处理其他事情,例如文件大小限制和多种可接受的 MIME 类型。

标签: javascript php html ajax canvas


【解决方案1】:

我遇到了同样的问题 - 看起来 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 标头引起的。使用结合 FormData 的基本 xhr 请求会强制 xhr 请求以 multipart/formdata 内容类型和正确定义的内容边界发送。

【讨论】:

    【解决方案2】:

    我怀疑你没有配置你的开发框来显示 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/');
    

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 2013-07-22
      • 2019-02-14
      • 2015-06-13
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      相关资源
      最近更新 更多