2

I am trying to save a captured image from HTML5/Canvas with a mobile. I am using PHP (symfony2). I followed the instructions from this post (How to save a PNG image server-side, from a base64 data source) but I get a dark empty image saved instead of what I captured.

Here is my JavaScript post code:

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

And the PHP saving code :

$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);
}
Community
  • 1
  • 1
ben muriel
  • 51
  • 1
  • 2
  • Possible duplicate of [How to save a PNG image server-side, from a base64 data string](http://stackoverflow.com/questions/11511511/how-to-save-a-png-image-server-side-from-a-base64-data-string) – ArrowHead Feb 08 '16 at 10:40
  • just curious, what happens if you do var dataUrl = canvas.toDataURL(); var img=document.createElement("img");img.src=dataUrl; document.body.appendChild(img); – hanshenrik Feb 08 '16 at 11:00
  • wow, i have the same problem, the base64 from CHROME 48 is useless (invalid png format), but the base64 from FIREFOX 43 works just fine! ... try your code in firefox, does it work then? – hanshenrik Feb 08 '16 at 11:24

1 Answers1

0

First of all, make sure to specify the datatype on the cliente side as

 dataType: 'text',

On the server side replace your first two statements with :

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

For further pointers take a loop at previously asked question

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

Community
  • 1
  • 1
ArrowHead
  • 609
  • 5
  • 16