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


当前回答

这个函数应该可以工作。它有一个photo参数,保存base64字符串,还有一个现有图像目录的路径,如果你已经有一个现有的图像,你想要在保存新图像时解除链接。

 public function convertBase64ToImage($photo = null, $path = null) {
    if (!empty($photo)) {
        $photo = str_replace('data:image/png;base64,', '', $photo);
        $photo = str_replace(' ', '+', $photo);
        $photo = str_replace('data:image/jpeg;base64,', '', $photo);
        $photo = str_replace('data:image/gif;base64,', '', $photo);
        $entry = base64_decode($photo);
        $image = imagecreatefromstring($entry);

        $fileName = time() . ".jpeg";
        $directory = "uploads/customer/" . $fileName;

        header('Content-type:image/jpeg');

        if (!empty($path)) {
            if (file_exists($path)) {
                unlink($path);
            }
        }

        $saveImage = imagejpeg($image, $directory);

        imagedestroy($image);

        if ($saveImage) {
            return $fileName;
        } else {
            return false; // image not saved
        }
    }
}

其他回答

如果您想随机重命名图像,并将图像路径存储在数据库中的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. :)

你需要从这个字符串中提取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);

这个函数应该可以工作。它有一个photo参数,保存base64字符串,还有一个现有图像目录的路径,如果你已经有一个现有的图像,你想要在保存新图像时解除链接。

 public function convertBase64ToImage($photo = null, $path = null) {
    if (!empty($photo)) {
        $photo = str_replace('data:image/png;base64,', '', $photo);
        $photo = str_replace(' ', '+', $photo);
        $photo = str_replace('data:image/jpeg;base64,', '', $photo);
        $photo = str_replace('data:image/gif;base64,', '', $photo);
        $entry = base64_decode($photo);
        $image = imagecreatefromstring($entry);

        $fileName = time() . ".jpeg";
        $directory = "uploads/customer/" . $fileName;

        header('Content-type:image/jpeg');

        if (!empty($path)) {
            if (file_exists($path)) {
                unlink($path);
            }
        }

        $saveImage = imagejpeg($image, $directory);

        imagedestroy($image);

        if ($saveImage) {
            return $fileName;
        } else {
            return false; // image not saved
        }
    }
}

我希望这对你有所帮助。 我用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

试试这个…

$file = $_POST['file']; //your data in base64 'data:image/png....';
$img = str_replace('data:image/png;base64,', '', $file);
file_put_contents('img/imag.png', base64_decode($img));