如何使用 php 在文件系统中保存 base64 解码的图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8252925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:17:10  来源:igfitidea点击:

How to save a base64 decoded image in the filesystem using php?

phpweb-servicesbase64

提问by Amit

I am getting a base64 encoded JPEG string via a POST request to my web service. I want to decode it and save it in the filesystem. How can I achieve this using PHP 5.3. I am able to successfully decode the data using the base64_decode function.

我通过对我的 Web 服务的 POST 请求得到一个 base64 编码的 JPEG 字符串。我想解码它并将其保存在文件系统中。我如何使用 PHP 5.3 实现这一点。我能够使用 base64_decode 函数成功解码数据。

How can I save this decoded string as a JPEG image in the server?

如何将此解码后的字符串保存为服务器中的 JPEG 图像?

Thanks in advance.

提前致谢。

回答by Lawrence Cherone

If you are sure the image will always be jpg then you can simply use: file_put_contents();

如果您确定图像始终为 jpg,那么您可以简单地使用:file_put_contents();

<?php 
$decoded=base64_decode($encodedString);

file_put_contents('newImage.JPG',$decoded);
//leave it to you to randomize the filename.
?>

回答by V.Vachev

Replacing the blank spaces with + signs is required if the data is derived from canvas.toDataURL() function.

如果数据来自 canvas.toDataURL() 函数,则需要用 + 符号替换空格。

 $encodedString = str_replace(' ','+',$encodedString);

See this question

看到这个问题

It helped a lot in my case.

在我的情况下,它有很大帮助。