如何在服务器上将HTML5画布保存为图像 [英] How to save a HTML5 Canvas as Image on a server

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

问题描述

我正在开发一个生成艺术项目,其中我想允许用户保存一个算法产生的图像。一般思路是:

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上创建图片


  • 允许用户下载图像或将其添加到使用算法生成的图片库中。
  • li>
  • create an image on HTML5 Canvas using generative algorithm
  • when the image is completed, allow user to save the canvas as an image file to server
  • Allow the user to either download the image or add it to a gallery of pieces of produced using the algorithm.

但是,我坚持的第二步:(我刚刚开始的javascript编程在上个月和php / AJAX,但认为(也许)这是一个合理的项目,通过它来学习。

However, I'm stuck on the second step :( I just started javascript programming in the last month and have very little experience with php/AJAX, but thought that (perhaps) this was a reasonable project to learn them through.

在google的帮助之后,我发现这博文,这似乎正是我想要的:

After some help from google, I found this blog post, which seemed to be exactly what I wanted:

这导致了javscript代码:

Which led to the javscript 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 :(

更多googling会显示此博客帖子

More googling turns up this blog post:

这是基于上一个教程,没有什么不同,但也许值得一试: p>

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;

这将创建一个文件(yay!),但它已损坏,似乎不包含任何内容。它也显示为空(文件大小为0)...

This one creates a file (yay!) but its 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.

EDIT:

按照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代码和datafile是〜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 :(

推荐答案

如何实现您需要的:

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>

2)将画布图转换为网址格式(base64) >

2) Convert canvas image to URL format (base64)

var dataURL = canvas.toDataURL();

3)通过Ajax将其发送到您的服务器 b
$ b

3) Send it to your server via 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.
});

3)将base64作为映像保存在服务器上 a href =http://stackoverflow.com/questions/1532993/i-have-a-base64-encoded-png-how-do-i-write-the-image-to-a-file-in-php >如何在PHP中这样做,同样的想法是在每种语言中。服务器端在PHP中可以在这里找到):

3) 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画布保存为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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