php - 将图像从浏览器发送到服务器 - 可能吗?

标签 php javascript html image canvas

有一个图片库网站,用户可以通过 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/

相关文章:

Javascript/PHP 撇号错误

javascript - 如何删除元素内的跨度?

html - 高级 CSS : top and bottom with flexible centre

jquery - 使用 jQuery 检查文本是否等于 html 特殊字符

javascript - 页面更改时 Div 滚动位置不会返回顶部

PHP:在异常中,异常代码的用途是什么?

php - 如何限制php mysql中的泰米尔语内容

php - 数据库上的搜索引擎(solr/sphinx)

php - 使用 Cron 作业/事件调度程序 30 分钟后删除 MySQL 行

javascript - 使用 Flash + JavaScript 进行客户端压缩