有一个图片库网站,用户可以通过 javascript 和 HTML5 canvas 操作图片。是否可以将处理后的图片传回服务器用PHP存储?
最佳答案
HERE您可以找到有关该主题的完整文章。但这里是简短版本和源代码:
首先您需要将 Canvas 二进制数据转换为 base 64 编码的字符串以将其发送到服务器:
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 脚本 save.php 如下所示:
<?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 脚本解析原始发布数据,将 base 64 转换为二进制,然后保存到文件中。有关 Base 64 的更多信息,请查看 THIS维基百科文章。
关于php - 将图像从浏览器发送到服务器 - 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123127/