如何保存为PNG图像服务器端,从一个base64数据串 [英] How to save a PNG image server-side, from a base64 data string
问题描述
我使用Nihilogic的Canvas2Image的JavaScript工具的画布绘图转换为PNG图像。
我现在需要的是把这个工具生成,转化为实际的PNG文件在服务器上的base64那些字符串,使用PHP。
I'm using Nihilogic's "Canvas2Image" JavaScript tool to convert canvas drawings to PNG images. What I need now is to turn those base64 strings that this tool generates, into actual PNG files on the server, using PHP.
总之,正是我目前做的是产生使用Canvas2Image客户端的文件,然后检索的base64恩codeD数据,并使用AJAX发送到服务器:
In short, what I'm currently doing is to generate a file on the client side using Canvas2Image, then retrieve the base64-encoded data and send it to the server using AJAX:
// Generate the image file
var image = Canvas2Image.saveAsPNG(canvas, true);
image.id = "canvasimage";
canvas.parentNode.replaceChild(image, canvas);
var url = 'hidden.php',
data = $('#canvasimage').attr('src');
$.ajax({
type: "POST",
url: url,
dataType: 'text',
data: {
base64data : data
}
});
在这一点上,hidden.php接收到一个数据块,看起来像 数据:图像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAABE ... 的
At this point, "hidden.php" receives a data block that looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...
从这点上,我pretty多难住了。从我读过,我相信我应该使用PHP的的 imagecreatefromstring 的功能,但我不知道如何真正从创建一个实际的PNG图像的Base64恩codeD字符串,并将其存储在我的服务器上。
请帮助!
From this point on, I'm pretty much stumped. From what I've read, I believe that I'm supposed to use PHP's imagecreatefromstring function, but I'm not sure how to actually create an actual PNG image from the base64-encoded string and store it on my server. Please aid!
推荐答案
您需要提取该字符串,德code将其以base64图像数据,然后可以将其保存到磁盘上,你不需要GD因为它已经是一个PNG。
You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
而作为一个班轮:
And as a one-liner:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
这篇关于如何保存为PNG图像服务器端,从一个base64数据串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!