2012-07-16 68 views
143

我正在使用Nihilogic的「Canvas2Image」JavaScript工具將畫布圖形轉換爲PNG圖像。 現在我需要的是使用PHP將這個工具生成的base64字符串轉換爲服務器上的實際PNG文件。如何從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」 接收,看起來像數據的數據塊:圖像/ PNG; BASE64,iVBORw0KGgoAAAANSUhEUgAABE ...

從這一點上,我幾乎難倒。從我讀過的,我相信我應該使用PHP的imagecreatefromstring函數,但我不知道如何從base64編碼的字符串實際創建實際的PNG圖像並將其存儲在我的服務器上。 請幫助!

+0

你需要解析它。你可以從那裏提取圖像類型,然後使用base64_decode並通過圖像類型將該字符串保存在一個文件中 – Constantin 2012-07-16 19:51:56

+0

@Constantine請問你更具體嗎? – 2012-07-16 19:53:11

+7

$ data = $ _REQUEST ['base64data']; $ image = explode('base64,',$ data); file_put_contents('img.png',base64_decode($ image [1])); – Constantin 2012-07-16 19:55:20

回答

295

你需要從一個字符串中提取的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 = 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); 
+0

您的示例中有$ type。這個價值應該是什麼? – Jon 2017-02-11 20:10:21

+1

@喬恩'$ type'被從爆炸分配一個值,取決於它是否是數據:圖像/ JPG或數據:圖像/ PNG等 – drew010 2017-02-16 16:17:32

+0

我得到這個錯誤:畸形的UTF-8字符可能不正確編碼 我應該怎麼做? – aldo 2017-07-02 09:02:49

97

試試這個:

file_put_contents('img.png', base64_decode($base64string)); 

file_put_contents docs

+3

我試過這個,但是它包括'data:image/png; base64,'這會破壞文件。 – 2013-09-03 19:13:15

+2

@MichaelCalkins也爲我打破。 drew010的答案似乎是始終如一的唯一解決方案。 – 2013-11-24 03:21:07

+14

如果你包含'data:image/png; base64',那麼你傳遞給'base64_decode'的字符串是無效的base64。你只需要發送數據,這就是drew010的答案所說明的。這個答案沒有任何問題。你不能複製和粘貼沒有理解,並期望它「只是工作」。 – Cypher 2014-05-07 20:51:28

30

我不得不更換與加符號的空間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); 

希望有所幫助。

2

試試這個...

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

嗯,你的解決方案上面所依賴的圖像是JPEG文件上。對於一般的解決方案,我用

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

它值得一說,討論的話題是在RFC 2397記錄 - 「數據」 URL方案(https://tools.ietf.org/html/rfc2397

因爲這個PHP有處理這種原生方式數據 - 「數據:流包裝」(http://php.net/manual/en/wrappers.data.php

所以,你可以很容易地操作使用PHP數據流:

$data = 'data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7'; 

$source = fopen($data, 'r'); 
$destination = fopen('image.gif', 'w'); 

stream_copy_to_stream($source, $destination); 

fclose($source); 
fclose($destination); 
8

所採取的@ 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); 
} 
2

單線性解決方案。

$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])); 
0

此代碼的工作對我來說,查看以下代碼:

<?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); 
?> 
相關問題