如何将 HTML5 Canvas 保存为服务器上的图像? [英] How to save an HTML5 Canvas as an image on a server?

查看:35
本文介绍了如何将 HTML5 Canvas 保存为服务器上的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个生成艺术项目,我希望允许用户通过算法保存生成的图像.总体思路是:

I'm working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • 使用生成算法在 HTML5 Canvas 上创建图像
  • 当图像完成后,允许用户将画布作为图像文件保存到服务器
  • 允许用户下载图像或将其添加到使用该算法制作的作品库中.

然而,我卡在了第二步.经过谷歌的一些帮助,我发现了这个 博文,这似乎正是我想要的:

However, I’m stuck on the second step. After some help from Google, I found this blog post, which seemed to be exactly what I wanted:

这导致了 JavaScript 代码:

Which led to the JavaScript code:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var ajax = new XMLHttpRequest();

  ajax.open("POST", "testSave.php", false);
  ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
  }
  ajax.setRequestHeader("Content-Type", "application/upload");
  ajax.send("imgData=" + canvasData);
}

和相应的PHP(testSave.php):

and corresponding PHP (testSave.php):

<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])) {
  $imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
  $filteredData = substr($imageData, strpos($imageData, ",") + 1);
  $unencodedData = base64_decode($filteredData);
  $fp = fopen('/path/to/file.png', 'wb');

  fwrite($fp, $unencodedData);
  fclose($fp);
}
?>

但这似乎根本没有任何作用.

But this doesn’t seem to do anything at all.

更多的谷歌搜索会出现这个 博客文章 基于上一个教程.没什么不同,但也许值得一试:

More Googling turns up this blog post which is based off of the previous tutorial. Not very different, but perhaps worth a try:

$data = $_POST['imgData'];
$file = "/path/to/file.png";
$uri = substr($data,strpos($data, ",") + 1);

file_put_contents($file, base64_decode($uri));
echo $file;

这个创建了一个文件(是的),但它已损坏并且似乎不包含任何内容.它也似乎是空的(文件大小为 0).

This one creates a file (yay) but it’s corrupted and doesn’t seem to contain anything. It also appears to be empty (file size of 0).

有什么明显的我做错了吗?我存储文件的路径是可写的,所以这不是问题,但似乎什么也没发生,我不确定如何调试.

Is there anything really obvious that I’m doing wrong? The path where I’m storing my file is writable, so that isn’t an issue, but nothing seems to be happening and I’m not really sure how to debug this.

按照 Salvidor Dali 的链接,我将 AJAX 请求更改为:

Following Salvidor Dali’s link I changed the AJAX request to be:

function saveImage() {
  var canvasData = canvas.toDataURL("image/png");
  var xmlHttpReq = false;

  if (window.XMLHttpRequest) {
    ajax = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    ajax = new ActiveXObject("Microsoft.XMLHTTP");
  }

  ajax.open("POST", "testSave.php", false);
  ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
  }
  ajax.send("imgData=" + canvasData);
}

现在图像文件已创建并且不为空!似乎内容类型很重要,将其更改为 x-www-form-urlencoded 允许发送图像数据.

And now the image file is created and isn’t empty! It seems as if the content type matters and that changing it to x-www-form-urlencoded allowed the image data to be sent.

控制台返回 base64 代码的(相当大的)字符串,数据文件约为 140 kB.但是还是打不开,好像没有格式化成图片.

The console returns the (rather large) string of base64 code and the datafile is ~140 kB. However, I still can’t open it and it seems to not be formatted as an image.

推荐答案

以下是如何实现您所需要的示例:

Here is an example of how to achieve what you need:

  1. 画一些东西(取自画布教程)

<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = 'blue';
  context.stroke();
</script>

  1. 将画布图像转换为 URL 格式 (base64)

var dataURL = canvas.toDataURL();

var dataURL = canvas.toDataURL();

通过 Ajax 将其发送到您的服务器

    $.ajax({
      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
      }
    }).done(function(o) {
      console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });

  1. 将 base64 保存为图像(这里是 如何在 PHP 中执行此操作,每个语言中都有相同的想法.PHP 中的服务器端可以在这里找到):
  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

这篇关于如何将 HTML5 Canvas 保存为服务器上的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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