dongzai3139 2015-07-29 15:54
浏览 645
已采纳

解码base64字符串会产生黑色矩形图像

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.';
  • 写回答

1条回答 默认 最新

  • dongxiong5546 2015-07-29 16:03
    关注

    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?

    UPDATE

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?