Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when saving canvas image server-side, from a base64 data string,it produce blank image

I have problem with saving canvas image in PHP. I get a blank .png file. I search a lot about this problem but cant find anything useful about this. Why does it save a blank image instead of rendering real image?

JavaScript code:

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 code:

<?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.';
?>
like image 935
mkafiyan Avatar asked Nov 11 '22 08:11

mkafiyan


1 Answers

I suspect you haven't configured your development box to display PHP error messages. You are defining a constant that is not a valid identifier:

define('localhost/samp/sample2/uploads', 'images/');

That means that you cannot use it directly:

$file = localhost/samp/sample2/uploads . uniqid() . '.png';

... should be triggering:

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

... and file will only contain the base file name (e.g. 53676a01cdb59.png) but not path component. You need to use this syntax:

$file = constant('localhost/samp/sample2/uploads') . uniqid() . '.png';

... or, even better, give the constant a sensible name:

define('DIR_UPLOADS', 'images/');
like image 186
Álvaro González Avatar answered Nov 14 '22 21:11

Álvaro González