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

允我心安 提交于 2019-11-26 15:39:35

问题


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

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?


回答1:


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 :).




回答2:


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

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




回答3:


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

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



来源:https://stackoverflow.com/questions/1532993/i-have-a-base64-encoded-png-how-do-i-write-the-image-to-a-file-in-php

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