I'm trying to get an image from canvas and save it with my php script. But when the script proceedes, I got a simple black rectangle instead of my canvas image (web-cam snapshot). Here is my code:
$img = $base64Img;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = "photo/" . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
What is the purpose of this line:
$img = str_replace(' ', '+', $img);
Don't think it is necessary. Otherwise all seems fine.
I usually use php explode
to isolate the data:
$exploded = explode(',', $img);
$base64 = $exploded[1];
$data = base64_decode($base64);
But str_replace
should also do the job.
Maybe the error is in the code that loads the image?
Purpose of that line is to encode the white space in the base64 data. This is also mentioned in this comment on php.net. Probably it would be better to use the PHP function urlencode
in such cases.
$data = base64_decode($data);
This line is probably causing the issues in this, since the data is not used as a data url but saved to a file directly.