問題描述
我有一個畫布,我想使用 ajax 和 php 將畫布上下文上傳到服務器.我希望最終輸出是存儲在服務器上的圖像.我已經使用表單完成了圖像上傳.但是現在我想讓畫布上下文將其轉換為圖像并上傳到服務器!
I have a canvas and I want to upload the canvas context to the server using ajax and php. I want the final output to be an image stored on the server. I have done image uploading using form. But now I want to get the canvas context convert it to image and upload to the server!
那么,我該怎么做?任何建議、算法或解決方案表示贊賞!
So, how can i do that? Any suggestions, algos or solutions are appreciated!
推薦答案
這篇博文恰當地描述了使用 AJAX 查詢將畫布保存到服務器上的方法,我想這應該適合您.
This blog post aptly describes the method of saving canvases onto the server with AJAX queries, I guess this should be fitting for you.
基本上,您需要一個 var canvasData = testCanvas.toDataURL("image/png");
以在 JavaScript 中檢索畫布的內容.這將是一個 Base64 編碼的字符串,如下所示:data:image/png;base64,fooooooooooobaaaaaaaaaaar==
.
Basically, you will need a var canvasData = testCanvas.toDataURL("image/png");
to retrieve the canvas' contents in JavaScript. This will be a Base64 encoded string, something like this: data:image/png;base64,fooooooooooobaaaaaaaaaaar==
.
以下代碼將確保 AJAX 查詢將內容發送到 HTML:
The following code will make sure the AJAX query sends the contents to the HTML:
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
在服務器上,在 PHP 腳本中,您將在 $GLOBALS
數組中有一個名為 HTTP_RAW_POST_DATA
的鍵,這將包含我們剛剛獲取的數據.>
On the server, in the PHP script, you will have a key named HTTP_RAW_POST_DATA
in the $GLOBALS
array, this will contain the data we just fetched.
// Remove the headers (data:,) part.
$filteredData=substr($GLOBALS['HTTP_RAW_POST_DATA'], strpos($GLOBALS['HTTP_RAW_POST_DATA'], ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$decodedData=base64_decode($filteredData);
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $decodedData);
fclose( $fp );
當然,test.png
是您要保存的文件名.第一行需要去掉編碼圖像的data:image/png;base64,
部分,以便以后可以通過base64_decode()
.它的輸出 ($decodedData
) 將保存到文件中.
Of course, test.png
is the filename you will save. The first line is required to remove the data:image/png;base64,
part of the encoded image, so that it can later be decoded by base64_decode()
. It's output ($decodedData
) will be saved to the file.
這篇關于使用 ajax 和 php 將畫布上下文作為圖像上傳的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!