php 如何从base64编码的jpeg创建GD图像​​?

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

How to create GD Image from base64 encoded jpeg?

phpimagegdbase64jpeg

提问by The Surrican

I have an upload Api that as a response object delivers (along with other stuff inside a Json object) a base64 encoded jpeg image.

我有一个上传 Api,它作为响应对象提供(以及 Json 对象中的其他内容)一个 base64 编码的 jpeg 图像。

I create the encoded image as so:

我这样创建编码图像:

$im; // gd image resource
ob_start();
imagejpeg($im);
$data = base64_encode(ob_get_clean());

The data then is put inside a form field using javascript and submitted.

然后使用 javascript 将数据放入表单字段中并提交。

How can I create a GD resource from that again so that I actually can save that image as a file?

如何再次从该资源创建 GD 资源,以便我可以将该图像保存为文件?

Everything in PHP.

PHP中的一切。

回答by

You can use imagecreatefromstring()function:

您可以使用imagecreatefromstring()函数:

$data = base64_decode($_POST['image_as_base64']);

$formImage = imagecreatefromstring($data);

"String" does not mean a "real" string. In that case it means bytes/blob data.

“字符串”并不意味着“真正的”字符串。在这种情况下,它意味着字节/blob 数据。

回答by Vilx-

How can I create a GD resource from that again so that I actually can save that image as a file?

如何再次从该资源创建 GD 资源,以便我可以将该图像保存为文件?

Are you sure you need to do that extra step? How about:

你确定你需要做那个额外的步骤吗?怎么样:

file_put_contents('MyFile.jpg', base64_decode($_POST['MyFormField']));

回答by Sarvar Nishonboev

I did by this way:

我是这样做的:

// input is in format: data:image/png;base64,...
$str="data:image/png;base64,"; 
$data=str_replace($str,"",$_POST['image']); 
$data = base64_decode($data);
file_put_contents('tmp/'.mktime().'.png', $data);