【问题标题】:Send image from browser to server - possible?将图像从浏览器发送到服务器 - 可能吗?
【发布时间】:2012-08-25 23:43:41
【问题描述】:

有一个图片库网站,用户可以通过 javascript 和 HTML5 画布操作图片。是否可以将处理后的图像发送回服务器以使用 PHP 存储?

【问题讨论】:

  • 一个很好的解决方案是JqueryUI Sortable,你想要纯javascript吗?
  • 不,当然可以使用 jquery。谢谢,我会看这个的。

标签: php javascript html image canvas


【解决方案1】:

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 Wikipedia 文章。

【讨论】:

    【解决方案2】:

    是的,canvas 支持将图像数据作为 Base64 编码的数据 url 或 Blob 返回。见http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-canvas-todataurl。然后,您可以获取数据 url 并使用 AJAX 将其发布到您的服务器,并在那里对其进行 Base64 解码。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      相关资源
      最近更新 更多