ben muriel February 2016

Dark image get while saving a png through PHP

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

Answers


ArrowHead February 2016

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

Post Status

Asked in February 2016
Viewed 1,993 times
Voted 14
Answered 1 times

Search




Leave an answer