doujian7132 2017-04-12 18:36
浏览 248
已采纳

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

I'm trying to get a .png image from <canvas> element generated basing on html code.

The javascript i'm using is:

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'); 
        });
  }
});
}

I have html2canvas library linked, it creates good <canvas> (can see them since I used appendChild), and now I'd like to convert those <canvas> into photo.png file, to be able to either save it on server, or INSERT INTO as blob to my `database table.

var dataURL = canvas.toDataURL();

to this point it seems everything is working fine (I can manage to get this url, which appears to be hella long). Because of strange look i'm pretty much sure i'd need to use base64 decoding to retrieve it as image file.

My imgprocess.php looks like that:

<?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);

?>

It does output photo.png file, but the file is empty and as I'm not very experienced I've been struggling to find cause of this issue.

Maybe you guys could help me deal with this problem?

  • 写回答

1条回答 默认 最新

  • duande3134 2017-04-12 18:43
    关注

    It should be $img = $_POST['imgBase64']; not $img = $_POST['data']; as your data object's key name is imgBase64 when sending the ajax post request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵