2014-10-29 72 views
0

我正在嘗試將畫布數據保存爲png文件。我正在使用以下ajax代碼並繼續獲取保存的圖像,但圖像已損壞。也許我有錯誤的$ _REQUEST屬性?Ajax保存畫布圖像已損壞(解碼不正確?)

任何幫助表示讚賞。

var dataURL = canvas.toDataURL('image/png'); 
    var imageURL; 
    $.ajax({ 
      url: "saveimage.php", 
      type: 'POST', 
      dataType: 'json', 
      data: { 'data_url': dataURL }, 
      complete: function(xhr, textStatus) { 
      // Request complete. 
      }, 
      // Request was successful. 
      success: function(response, textStatus, xhr) { 
       console.log('Response: ', response); 
       // Conversion successful. 
       if (response.status_code === 200) { 
        imageURL = response.data.image_url; 
        // Paste the PNG image url into the input field. 
        document.querySelector('img').src = imageURL; 
       } 
      }, 
      error: function(xhr, textStatus, errorThrown) { 
       // Some error occured. 
       console.log('Error: ', errorThrown); 
      } 
     }); 
} 

<?php 
file_put_contents('images/'. rand().'.png', base64_decode($_REQUEST['data_url'])); 
?> 

回答

2

所以,事實證明,這樣做的方式是分開的數據爆炸,因爲datatoURL實際上包含比我們需要的圖像更多的信息。此代碼爲我工作,並希望它可以幫助其他人:

<?php 
$data = $_REQUEST['data_url']; 
list($t, $data) = explode(';', $data); 
list(, $data)  = explode(',', $data); 
$data = base64_decode($data); 
$filename='images/'. rand().'.png'; 
file_put_contents($filename, $data); 
$response = array("image_url"=>$filename,"status_code"=>200); 
echo json_encode($response); 
?>