2012-03-04 99 views
3

的完整代码,也可以在这里找到:https://gist.github.com/1973726(部分版本上的jsfiddle http://jsfiddle.net/VaEAJ/显然不能让PHP与运行的jsfiddle)由JavaScript Canvas API生成的图像在保存时不可见?

我最初写了一些代码,花了canvas元素,并将其保存为图像(见工作代码在这里:https://gist.github.com/1973283),然后我更新它,以便它可以处理多个画布元素,但现在的主要区别是图像数据通过jQuery ajax方法传递到我的PHP脚本,而不是通过隐藏的表单字段。

问题是图像显示为空白。它们在生成时大约为200kb,因此它们显然有一些内容,但是当您预览图像时什么也没有显示,当我尝试在Adobe Fireworks或其他照片应用程序中打开图像时,我无法打开文件。

图像数据似乎是通过服务器罚款,但我真的不知道为什么现在当我写图像使用base64_decode这将意味着生成的图像将不再是可见的?我唯一能想到的是,也许通过ajax发布的数据并不是通过发送所有数据,因此它会生成一个图像,但它不是完整的内容,因此图像不完整(因此为什么照片应用程序可以'打开它)。

当检查Firebug中的发布数据时,它表明已达到限制?不知道这是什么问题?

+0

能否请您提供使用jQuery AJAX在你的代码更新的例子吗? – 2012-03-04 17:30:38

+0

1)我很惊讶它可以在所有因为交叉来源问题2)你似乎没有编码数据的URI,尝试'encodeURIComponent(newCanvas.toDataURL())'在将数据传递给jQuery的ajax方法。 – James 2012-03-04 18:30:38

回答

2

问题实际上是通过XHR发送数据。我最初使用jQuery ajax方法,然后将其交换出我自己的ajax抽象,但问题仍然存在,直到有人在Twitter上建议我使用FormData将数据传递到服务器端PHP。示例如下...(完整的代码可以在这里看到:https://gist.github.com/1973726

// Can't use standard library AJAX methods (such as…) 
// data: "imgdata=" + newCanvas.toDataURL() 
// Not sure why it doesn't work as we're only abstracting an API over the top of the native XHR object? 
// To make this work we need to use a proper FormData object (no data on browser support) 
var formData = new FormData(); 
formData.append("imgdata", newCanvas.toDataURL()); 

var xhr = new XMLHttpRequest(); 
xhr.open("POST", "saveimage.php"); 
xhr.send(formData); 

// Watch for when the state of the document gets updated 
xhr.onreadystatechange = function(){ 
    // Wait until the data is fully loaded, and make sure that the request hasn't already timed out 
    if (xhr.readyState == 4) { 
     // Check to see if the request was successful 
     if (checkHTTPSuccess(xhr)) { 
      // Execute the success callback 
      onSuccessfulImageProcessing(card, newCanvas, ctx, getHTTPData(xhr)); 
     } 
     else { 
      throw new Error("checkHTTPSuccess failed = " + e); 
     } 

     xhr.onreadystatechange = null; 
     xhr = null; 
    } 
}; 

```

0

如果您没有Cross Origin SECURITY_ERR(您的小提琴受到影响,但只要您的图像在同一台服务器上,它们就会没事),并且您正在收集一些数据,因此您可能遇到了问题PHP。在PHP user notes中,您必须用空格替换空格才能解码使用Javascript编码的base64。

$data = str_replace(" ", "+", $_POST['imgdata']); 
file_put_contents("generated.png", base64_decode($data));