通过php将Canvas数据发送到图像文件

时间:2015-08-04 14:23:47

标签: javascript php html5-canvas

所以经过多年的观察,我发现this post这是我问题的答案。当我尝试它时,图像文件已创建,但其中没有任何数据。这是我的代码如下。如果我遗漏了一些内容或任何可以使图像文件可读的更正,你能告诉我吗?

谢谢

index.html

<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="364.8" height="220.8" style=" border:1px solid #d3d3d3;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
     var context = canvas.getContext("2d");
     var imageObj = new Image();
     imageObj.onload = function(){
         context.drawImage(imageObj, 0, 0);
         context.font = "20pt Tahoma";
         context.fillStyle = '#3a3a3a';
         context.fillText("TEST", 20, 100);
         context.font = "15pt Tahoma";
         context.fillStyle = '#3a3a3a';
         context.fillText("youremail@something.com", 20, 130);

     };
     imageObj.src = "T1.png";    
var testCanvas = document.getElementById('myCanvas');
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'http://www.lapisdesigns.tk/Lapisdesigns/process.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send("canvasData"+canvasData );     
</script>
</body>
</html>

process.php

<?php
$rawData = $_POST['imageData'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
//Create the image 
$fp = fopen('sigs/test1.png', 'w');
fwrite($fp, $unencoded);
fclose($fp); 
$file_name = 'test1.png';
$file_size = strlen($filteredData[1])/1024; //This may be wrong, doesn't seem to break for me though.
$fh = fopen('sigs/test1.png', 'r');
$content = fread($fh, $file_size);
$content = base64_encode($content);
fclose($fh);
?>

1 个答案:

答案 0 :(得分:0)

ajax.send("canvasData"+canvasData );     
            ^^^^^^^^

$rawData = $_POST['imageData'];
                   ^^^^^^^^

由于您没有=,因此您只需发送一个非常长的canvasDatablahblahblah密钥名称,而不会发送任何值。即使键名正确设置为canvasData,您的PHP代码也在寻找一个完全不同的名称imageData

尝试

ajax.send("imageData=" + canvasData);
           ^^^^^^^^^--- note new new
                    ^---note the = 

代替。