2015-07-29 15:54
浏览 468


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.';

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从画布中获取图像并使用我的php脚本保存它。 但是当脚本出现时,我得到了一个简单的黑色矩形而不是我的画布图像(网络摄像头快照)。 这是我的代码:

  $ 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:'无法保存文件。'; 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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?


    Purpose of that line is to encode the white space in the base64 data. This is also mentioned in this comment on 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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题