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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法