我使用Nihilogic的“Canvas2Image”JavaScript工具将画布图纸转换为PNG图像。 我现在需要的是使用PHP将该工具生成的base64字符串转换为服务器上的实际PNG文件。

简而言之,我目前所做的是在客户端使用Canvas2Image生成一个文件,然后检索base64编码的数据并使用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…

从现在起,我几乎被难住了。从我所读到的,我相信我应该使用PHP的imagecreatefromstring函数,但我不确定如何从base64编码的字符串实际创建一个PNG图像并将其存储在我的服务器上。 请帮助!


当前回答

我希望这对你有所帮助。 我用core php方法解决了这个问题。 我解决的代码如下。

$base64string = 'BASE64 STRING GOES HERE';
$uploadpath   = 'YOUR UPLOAD DIR PATH';
$parts        = explode(";base64,", $base64string); //THIS WILL GET THE ORIGINAL FILE ENCODE STRING
$imagebase64  = base64_decode($parts[1]); //THIS WILL GET THE DECODED IMAGE STRING
$file         = $uploadpath . uniqid() . '.png'; // THIS WILL GIVE THE FILE NAME AND SET THE FILE PATH
file_put_contents($file, $imagebase64); // THIS FUNCTION WILL STORE THE IMAGE TO GIVEN PATH WITH FILE_NAME

其他回答

你需要从这个字符串中提取base64图像数据,解码它,然后你可以将它保存到磁盘,你不需要GD,因为它已经是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));

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

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

很简单:

让我们想象一下,你正在尝试在js框架中上传一个文件,ajax请求或移动应用程序(客户端)

首先,发送一个包含base64编码的数据属性 字符串。 在服务器端,您必须解码并将其保存在本地 项目文件夹。

这里是如何使用PHP

<?php 

$base64String = "kfezyufgzefhzefjizjfzfzefzefhuze"; // I put a static base64 string, you can implement you special code to retrieve the data received via the request.

$filePath = "/MyProject/public/uploads/img/test.png";

file_put_contents($filePath, base64_decode($base64String));

?>

好吧,上面的解决方案取决于图像是一个jpeg文件。我用的是通解

$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));

假设你在$filename中有文件名,在$testfile my onlineer中有base64encoded字符串:

写入(文件名,美元base64_decode(爆炸(',' $测试文件)[1]))

基于drew010的例子,我做了一个工作的例子,便于理解。

imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 

function imagesaver($image_data){

    list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 

    if (preg_match('/^data:image\/(\w+);base64,/', $image_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 = base64_decode($data);

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

    $fullname = time().$type;

    if(file_put_contents($fullname, $data)){
        $result = $fullname;
    }else{
        $result =  "error";
    }
    /* it will return image name if image is saved successfully 
    or it will return error on failing to save image. */
    return $result; 
}