如何从 base64 数据 URI 保存 PNG 图像服务器端 [英] How to save a PNG image server-side, from a base64 data URI

查看:37
本文介绍了如何从 base64 数据 URI 保存 PNG 图像服务器端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Nihilogic 的Canvas2Image"JavaScript 工具将画布绘图转换为 PNG 图像.我现在需要的是使用 PHP 将这个工具生成的那些 base64 字符串转换为服务器上的实际 PNG 文件.

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 编码的数据并使用 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"收到一个看起来像data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...

At this point, "hidden.php" receives a data block that looks like data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABE...

从这一点开始,我几乎被难住了.从我读过的内容来看,我相信我应该使用 PHP 的 imagecreatefromstring 函数,但我不确定如何从 base64 编码的字符串实际创建实际的 PNG 图像并存储它在我的服务器上.请帮忙!

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!

推荐答案

您需要从该字符串中提取 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);

作为单线:

$data = base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $data));

提取、解码和检查错误的有效方法是:

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image/(w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new Exception('base64_decode failed');
    }
} else {
    throw new Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

这篇关于如何从 base64 数据 URI 保存 PNG 图像服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆