2012-12-10 120 views
4

我有這樣如何將圖像從canvas標籤保存到php服務器?

var testCanvas = document.getElementById('canvas-1'); 
var canvasData = testCanvas.toDataURL("image/png"); 
var ajax = new XMLHttpRequest(); 
ajax.open("POST",'http://www.domain.com/imgsave.php',true); 
ajax.setRequestHeader('Content-Type', 'canvas/upload'); 
ajax.send("canvasData"+canvasData); 

我的PHP代碼中的JavaScript代碼是這樣

if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) 
{ 
    // Get the data 
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA']; 

    $filteredData=substr($imageData, strpos($imageData, ",")+1); 

    $unencodedData=base64_decode($filteredData); 
    $fp = fopen('test.png', 'wb'); 
    fwrite($fp, $unencodedData); 
    fclose($fp); 
     echo "saved"; 
} 
    else{ 

    echo "no raw data"; 
    } 

執行此代碼時,我得到一個零尺寸PNG文件的圖像?我的代碼有什麼問題?

+2

當然,你檢查'$ unencodedData'不是空的,對吧? – dfsq

回答

6

我最近不得不自己做這個。

首先,我把我的canvasData放入一個隱藏字段並將其發佈到我的PHP頁面。

它回來格式爲:data:image/png;base64,iVBORw0......

您需要了第一分割數據,因爲這:data:image/png;base64,是頭信息。其餘的是編碼數據。

$rawData = $_POST['imageData']; 
$filteredData = explode(',', $rawData); 

$unencoded = base64_decode($filteredData[1]); 

我然後創建我的服務器上的圖像:

//Create the image 
$fp = fopen('sigs/test1.png', 'w'); 
fwrite($fp, $unencoded); 
fclose($fp); 

,然後閱讀它做任何我想做的事情。

$file_name = 'test1.png'; 
$file_size = strlen($filteredData[1])/1024; //This may be wrong, doesn't seem to break for me though. 


$fh = fopen('sigs/test1.png', 'r'); 
$content = fread($fh, $file_size); 
$content = base64_encode($content); 
fclose($fh); 

我更確定有一個更優雅的解決方案,但這一直在爲我工作!

檢查本作的詳細信息(可能):My own question

0

根據comment in the manual,得到HTTP_RAW_POST_DATA,你需要做的是這樣的:

<?php $postdata = file_get_contents("php://input"); ?> 

手冊說,這對包裝如php://input

在POST請求的情況下,優選的是使用PHP://輸入 而不是$ HTT P_RAW_POST_DATA,因爲它不依賴於特殊的012.php.ini指令。

2

這是我做的事從畫布通過ajax保存圖像。我使用jQuery在客戶端

jQuery.ajax({ 
    url: 'save.php', 
    type: 'POST', 
    data: { 
     data: c.toDataURL('image/png') 
    }, 
    complete: function(data, status) 
    { 
     if(status=='success') 
     { 
      alert('saved!'); 
     } 
     alert('Error has been occurred'); 
    } 

}); 

PHP:

$based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1); 

    $image = imagecreatefromstring(base64_decode($based64Image)); 

    $fileName=''; 
    if($image != false) 
    { 
     $fileName=time().'.png'; 
     if(!imagepng($image, $fileName)) 
     { 
//   fail; 
     } 
    } 
    else 
    { 
//   fail; 
    } 

我希望這有助於。

相關問題