有一个图片库网站,用户可以通过javascript和HTML5画布操作图片。是否可能将处理后的图片发送回服务器以便使用PHP进行存储?
有一个图片库网站,用户可以通过javascript和HTML5画布操作图片。是否可能将处理后的图片发送回服务器以便使用PHP进行存储?
您可以在这里找到有关此主题的完整文章。但这是简短的版本和源代码:
首先,您需要将画布二进制数据转换为Base64编码字符串,然后将其发送到服务器:
var image = canvas.toDataURL("image/png");
使用ajax调用发送此内容:
var ajax = new XMLHttpRequest();
ajax.open("POST",'save.php', false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(image);
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
这个 PHP 脚本会解析原始的 post 数据,并将其从 base 64 转换为二进制数据,最终保存为文件。如需了解 Base 64 的更多信息,请查看此维基百科文章。
是的,canvas支持将图像数据作为Base64编码的数据URL或Blob返回。请参见http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl。然后,您可以获取数据URL并使用AJAX将其发送到服务器,然后在那里对其进行Base64解码。