我有一个 base64 编码的 png,如何将图像写入 PHP 中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1532993/
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-25 02:59:09  来源:igfitidea点击:

I have a base64 encoded png, how do I write the image to a file in PHP?

phppnggd

提问by mmattax

What's the proper way in PHP to create an image file (PNG), when I have the base64 encoding?

当我使用 base64 编码时,在 PHP 中创建图像文件 (PNG) 的正确方法是什么?

I've been playing around with:

我一直在玩:


file_put_contents('/tmp/'. $_REQUEST['id'].'.png', $_REQUEST['data']);

do I need to decode? should I be using the gd library?

我需要解码吗?我应该使用 gd 库吗?

采纳答案by Thibault Martin-Lagardette

My best guess is that you simply need to call base64_decode()on $_REQUEST['data']before writing it to the file. That should be plenty enough :).

我最好的猜测是,你只需要调用base64_decode()$_REQUEST['data']其写入文件之前。那应该足够了:)。

回答by Yevgeniy Afanasyev

You need to use base64_decode(). AND. Sometimes it is not sufficient. Here is all code that you need:

您需要使用 base64_decode()。和。有时这还不够。这是您需要的所有代码:

$img = $_POST['data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);

P.S. I used this code to get PNG image from html canvas.

PS我使用此代码从html画布获取PNG图像。

回答by Chris Kloberdanz

I would think you'd want to decode with base64_decode()unless you are only using it like they are here HERE.

我想你会想用base64_decode()解码,除非你只是像他们在这里一样使用它。

The thing I am sure of is that you will want to sanitize $_REQUEST['id'] before using it.

我可以肯定的是,您需要在使用 $_REQUEST['id'] 之前对其进行清理。