【问题标题】:Dark image get while saving a png through PHP通过PHP保存png时出现深色图像
【发布时间】:2016-05-17 23:04:51
【问题描述】:

我正在尝试使用移动设备保存从 HTML5/Canvas 捕获的图像。我正在使用 PHP (symfony2)。 我按照这篇文章 (How to save a PNG image server-side, from a base64 data source) 中的说明进行操作,但我保存了一张深色的空白图像,而不是我捕获的图像。

这是我的 JavaScript 帖子代码:

var dataUrl = canvas.toDataURL();
$.ajax({
    type: "POST",
    url: "{{ path("personne_photo_capture",{"id":entity.personne.id}) }}",
    data: {
        imgBase64: dataUrl
    }
}).done(function (msg) {
    $('#msg').html(msg); 

}).fail(function (xhr, textStatus, errorThrown) {
    $('#msg').html(xhr.responseText);
}); 

还有 PHP 保存代码:

$rawData = $_POST['imgBase64'];
if (isset($rawData)) {
    $filteredData = explode('base64,', $rawData);
    $data = base64_decode($filteredData[1]);  
    $filename = "profil.png";
     file_put_contents('picts/small/' . $filename, $data);
}

【问题讨论】:

  • 只是好奇,如果你这样做会发生什么 var dataUrl = canvas.toDataURL(); var img=document.createElement("img");img.src=dataUrl; document.body.appendChild(img);
  • 哇,我也有同样的问题,来自 CHROME 48 的 base64 没用(无效的 png 格式),但来自 FIREFOX 43 的 base64 工作得很好! ...在 Firefox 中尝试您的代码,它可以工作吗?

标签: php html html5-canvas


【解决方案1】:

首先,确保在客户端指定数据类型为

 dataType: 'text',

在服务器端将前两个语句替换为:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

对于进一步的指针,请在先前提出的问题处循环

How to save a PNG image server-side, from a base64 data string

【讨论】:

  • 爆炸代码对我来说看起来不错,我怀疑 preg_replace 会做得更好
猜你喜欢
  • 1970-01-01
  • 2018-07-25
  • 2018-12-12
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2015-05-17
相关资源
最近更新 更多