How to create GD Image from base64 encoded jpeg?

五迷三道 提交于 2019-12-03 11:45:14

问题


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

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.

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

Everything in PHP.


回答1:


You can use imagecreatefromstring() function:

$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.




回答2:


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

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

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



回答3:


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);


来源:https://stackoverflow.com/questions/4572121/how-to-create-gd-image-from-base64-encoded-jpeg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!