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

解码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.

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

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题