上传画布背景为图像使用AJAX和PHP [英] uploading canvas context as image using ajax and php

查看:205
本文介绍了上传画布背景为图像使用AJAX和PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

那么,我该怎么办呢?任何建议,交易算法或解决方案AP preciated!

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(图像/ PNG); 来检索JavaScript的画布的内容。这将是一个的Base64 EN codeD字符串,像这样:数据:图像/ 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==.

下面code将确保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脚本中,你将有一个名为 HTTP_RAW_POST_DATA $ GLOBALS 数组的关键,这将包含的数据,我们只是空穴来风。

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 是文件名,你会救。第一行需要删除数据:图像/ PNG;带连接codeD映像的base64,部分,这样以后就可以去codeD通过 base64_de code() 。它的输出( $日codedData )将被保存到文件中。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆