我使用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图像并将其存储在我的服务器上。 请帮助!


当前回答

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

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

其他回答

基于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; 
}

采用@dre010的想法,我已经将其扩展到另一个函数,该函数适用于任何图像类型:PNG, JPG, JPEG或GIF,并为文件名提供了唯一的名称

该功能分离图像数据和图像类型

function base64ToImage($imageData){
    $data = 'data:image/png;base64,AAAFBfj42Pj4';
    list($type, $imageData) = explode(';', $imageData);
    list(,$extension) = explode('/',$type);
    list(,$imageData)      = explode(',', $imageData);
    $fileName = uniqid().'.'.$extension;
    $imageData = base64_decode($imageData);
    file_put_contents($fileName, $imageData);
}

如果您想随机重命名图像,并将图像路径存储在数据库中的blob和图像本身存储在文件夹中,这个解决方案将帮助您。您的网站用户可以存储尽可能多的图像,而图像将随机重命名为安全目的。

Php代码

生成随机varchars作为图像名称。

function genhash($strlen) {
        $h_len = $len;
        $cstrong = TRUE;
        $sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
        return bin2hex($sslkey);
}
$randName = genhash(3); 
#You can increase or decrease length of the image name (1, 2, 3 or more).

从image中获取图像数据扩展名和base_64部分(data:image/png;base64之后的部分)。

$pos  = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];

if(in_array($imgExten, $extens)) {

   $imgNewName = $randName. '.' . $imgExten;
   $filepath = "resources/images/govdoc/".$imgNewName;
   $fileP = fopen($filepath, 'wb');
   $imgCont = explode(',', $base64_img);
   fwrite($fileP, base64_decode($imgCont[1]));
   fclose($fileP);

}

# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.

# Please don't forget to up vote if you like my solution. :)

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

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

这段代码为我检查以下代码:

<?php
define('UPLOAD_DIR', 'images/');
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $image_base64);
?>