上传画布图像数据会产生空白图像

时间:2013-05-04 11:40:21

标签: php javascript html5 image canvas

我正在使用ajax查询来上传画布图像数据以及一些其他变量。以下是客户端相关代码的含义:

front_content = document.getElementById("front_paint_canvas").toDataURL("image/png");

ajaxHandler.open("POST", "upload_card", true);
ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxHandler.send("name="+name+"&front_content="+front_content);

这就是我在服务器端的内容:

$front_content = substr($_POST['front_content'], strpos($_POST['front_content'], ",")+1);

$decodedData=base64_decode($front_content);

$fp = fopen( getcwd().'/assets/img/canvas.png', 'wb' );
fwrite( $fp, $decodedData);
fclose( $fp );

这会创建一个看似正确尺寸的文件,并且该文件的尺寸也是正确的。但是,该文件为空。画布中没有任何图像数据显示出来。这里做错了什么?

1 个答案:

答案 0 :(得分:0)

使用jQuery.post()时请参阅:http://api.jquery.com/jQuery.post/“”application / x-www-form-urlencoded“不需要内容类型:

的javascript:

  // save canvas image as data url (png format by default)
  var dataURL = canvas.toDataURL();
  $.post("canvasdata.php", { data: dataURL } );

PHP:

//参见:How to save a html5 Canvas.toDataURl string as a png on a php backend string-as-a-png-on-a-php-backend

 file_put_contents('test.png', base64_decode(substr($_POST['data'], strpos($_POST['data'], ",")+1)));

<强>更新 如果你不使用jquery,请使用:

  // save canvas image as data url (png format by default)
  var dataURL = canvas.toDataURL();
  //$.post("canvasdata.php", { data: dataURL } );

  var ajaxHandler = new XMLHttpRequest();
  ajaxHandler.open("POST", "canvasdata.php", true);
  //ajaxHandler.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  //ajaxHandler.send("name=test&data="+dataURL);
  var formData = new FormData();
  formData.append("name", "test");
  formData.append("data", dataURL);
  ajaxHandler.send(formData);