Php 如何从base64数据URI保存PNG图像服务器端
我正在使用Nihilogic的“Canvas2Image”JavaScript工具将画布图形转换为PNG图像。 我现在需要的是使用PHP将此工具生成的base64字符串转换为服务器上的实际PNG文件 简言之,我目前正在使用Canvas2Image在客户端生成一个文件,然后检索base64编码的数据,并使用AJAX将其发送到服务器:Php 如何从base64数据URI保存PNG图像服务器端,php,javascript,base64,html5-canvas,Php,Javascript,Base64,Html5 Canvas,我正在使用Nihilogic的“Canvas2Image”JavaScript工具将画布图形转换为PNG图像。 我现在需要的是使用PHP将此工具生成的base64字符串转换为服务器上的实际PNG文件 简言之,我目前正在使用Canvas2Image在客户端生成一个文件,然后检索base64编码的数据,并使用AJAX将其发送到服务器: // Generate the image file var image = Canvas2Image.saveAsPNG(canvas, true); im
// 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,Ivborw0kgoaaaansuhueugabe…
从现在起,我几乎被难住了。从我所读到的内容来看,我相信我应该使用PHP的imagecreatefromstring函数,但我不确定如何从base64编码字符串实际创建一个PNG图像并将其存储在我的服务器上。
请帮忙 试试这个:
file_put_contents('img.png', base64_decode($base64string));
您需要从该字符串中提取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);
我必须用加号替换空格
str_replace(“,+”,$img)代码>以使其正常工作
这是完整的代码
$img = $_POST['img']; // Your data 'data:image/png;base64,AAAFBfj42Pj4';
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/tmp/image.png', $data);
希望有帮助。试试这个
$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));
上面的解决方案取决于图像是jpeg文件。对于我使用的一般解决方案
$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));
值得一提的是,讨论的主题记录在RFC 2397“数据”URL方案中()
正因为如此,PHP有一种处理此类数据的本机方法——“数据:流包装器”()
因此,您可以轻松地使用PHP流操作数据:
$data='数据:image/gif;base64,R0LGODLHEAAOALMAAOAZTOEH0TLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///YH5BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAA4AAREEKYKYK67QZ1HLNJUM5UUDE0ECWLJOEXKCPPV0ACCMCMTHIUEQGAORCMXIC6E0CCGUWW6AFJSVMKKIR7G77ZKKZKPJJJJJJYD7SJAGAG2XSB7ZBXXQYP7';
$source=fopen($data,'r');
$destination=fopen('image.gif','w');
流\u复制\u到\u流($source,$destination);
fclose($来源);
fclose(目的地);
采用@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);
}
一个线性解
$base64string = 'data:image/png;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7';
file_put_contents('img.png', base64_decode(explode(',',$base64string)[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);
?>
此功能应能正常工作。这有一个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
}
}
}
基于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;
}
总体关切:
$data = 'data:image/png;base64,AAAFBfj42Pj4';
// Extract base64 file for standard data
$fileBin = file_get_contents($data);
$mimeType = mime_content_type($data);
// Check allowed mime type
if ('image/png'==$mimeType) {
file_put_contents('name.png', $fileBin);
}
很简单:
假设您正试图在js框架、ajax请求或移动应用程序(客户端)中上载文件
首先,发送一个数据属性,该属性包含base64编码的
绳子
在服务器端,您必须对其进行解码并将其保存在本地文件中
项目文件夹
这里介绍如何使用PHP实现
如果您想随机重命名图像,并将图像路径作为blob存储在数据库中,将图像本身存储在文件夹中,此解决方案将帮助您。您的网站用户可以存储任意数量的图像,而出于安全目的,这些图像将被随机重命名
Php代码
生成随机VARCHAR以用作图像名称
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).
从图像中获取图像数据扩展名和base_64部分(数据后的部分: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. :)
$pos=strpos($base64_img,;);
$imgExten=explode('/',substr($base64_img,0,$pos))[1];
$extens=['jpg'、'jpe'、'jpeg'、'jfif'、'png'、'bmp'、'dib'、'gif'];
if(在数组中($imgExten,$extens)){
$imgNewName=$randName...$imgExten;
$filepath=“resources/images/govdoc/”$imgNewName;
$fileP=fopen($filepath,'wb');
$imgCont=explode(“,”,$base64_img);
fwrite($fileP,base64_解码($imgCont[1]);
fclose($fileP);
}
#=>$filepathPHP已经得到了公平对待base64->file transform
我通常通过以下方式完成:
$blob=$_POST['blob']; // base64 coming from an url, for example
$blob=file_get_contents($blob);
$fh=fopen("myfile.png",'w'); // be aware, it'll overwrite!
fwrite($fh,$blob);
fclose($fh);
echo '<img src=myfile.png>'; // just for the check
$blob=$\u POST['blob'];//例如,base64来自url
$blob=文件获取内容($blob);
$fh=fopen(“myfile.png”,“w”);//请注意,它将覆盖!
fwrite($fh,$blob);
fclose($fh);
回显“”;//只是为了检查一下
您需要解析它。您可以从中提取图像类型,然后使用base64_解码并通过图像将该字符串保存在文件中type@Constantine你能说得更具体些吗?$data=$_请求['base64data']$图像=分解('base64',$data);文件内容('img.png',base64解码($image[1]);你可以发布完整的代码,从快照到发送数据,这对我来说不起作用;base64,
这会破坏文件。@MichaelCalkins也会为我破坏它。drew010的答案似乎是唯一一个能持续工作的解决方案;base64,
则传递给base64\u decode
的字符串无效base64。您只需要发送数据,这就是drew010的答案所说明的。这个答案没有任何问题。您不能在不理解的情况下复制和粘贴,并期望它“正常工作”。问题中提供的示例不起作用,它不是base64内容,首先必须拆分为多个部分(请参见接受的答案)。我的图像已成功保存。但当我写图片的url时,我看到一个空白图片。我确信我的dataURL是正确的,因为我使用window.open(dataURL)测试了它。为什么是空白图像?您的示例中有$type。这个值应该是什么?@Jon$type
从分解中获得一个值,这取决于它是data:image/jpg还是data:image/png等。我得到了这个错误:格式错误的utf-8字符可能不正确
$blob=$_POST['blob']; // base64 coming from an url, for example
$blob=file_get_contents($blob);
$fh=fopen("myfile.png",'w'); // be aware, it'll overwrite!
fwrite($fh,$blob);
fclose($fh);
echo '<img src=myfile.png>'; // just for the check