使用 ajax 和 php 将画布上下文作为图像上传

2021-12-21 00:00:00 file-upload canvas php html ajax

我有一个画布,我想使用 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.

相关文章