2017-02-18 45 views
0

我想从客户端的画布上获取图像数据,并将其保存为我的服务器上的.png。php画布到服务器上的图像

这是从画布获取图像数据并将其发送到saveImage.php我的客户端代码:

function render() 
    { 

     var imageData = ctx.canvas.toDataURL("image/png"); 
     var postData = "imageData="+imageData; 

     var ajax = new XMLHttpRequest(); 
     ajax.open("POST","saveImage.php",true); 
     ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
     ajax.onreadystatechange=function() 
     { 
      console.log(ajax.responseText); 
     } 

     ajax.send(postData); 
    } 

而这正是saveImage.php样子:

<?php 
    if(isset($_POST["imageData"])) 
    { 
     $imageEncoded = $_POST["imageData"]; 

     $imageDataExploded = explode(',', $imageEncoded); 

     $imageDecoded = base64_decode($imageDataExploded[1]); 

     $filename = time()."image".mt_rand(); 

     $file = fopen("./".$filename.".png","wb"); 
     fwrite($file, $imageDecoded); 
     fclose($file); 
     echo $filename; 
     exit(); 
    } 
?> 

代码实际上工作正常,我的问题只是在某些方面创建的图像有问题。 当我尝试打开它时,windows说它不能显示图像,因为它不支持格式?即使它是一个.png?

我在做什么错在这里?

+0

您是否使用文本编辑器或十六进制编辑器查看了文件上下文,并将其与原始文件进行了比较?你看到什么差异? –

回答

0

你应该encodeURIComponent()包括它在POST数据之前编码数据。

您还应该使用像jQuery这样的框架来解决浏览器差异问题。我保证代码在所有浏览器中都不会起作用。

在PHP上,请尝试查看file_put_contents()以撰写数据。打字速度更快!

0

您是否检查过实际通过HTTP发送的内容? $ imageEncoded大概始于数据:图像/ PNG; BASE64,为XXXXX

地带的一切行动,以逗号BASE64后:

https://stackoverflow.com/a/15153931/3766670

+0

我编辑脚本以删除“data:image/png; base64”,但它仍然无效:( – stav

相关问题