如何挽救canvas标签图像PHP服务器? [英] How save image from canvas tag to php server?

查看:90
本文介绍了如何挽救canvas标签图像PHP服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript code这样

I have a javascript code like this

var testCanvas = document.getElementById('canvas-1');
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'http://www.domain.com/imgsave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send("canvasData"+canvasData );

我的PHP code是这样

My php code is like this

if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
    // Get the data
    $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

    $filteredData=substr($imageData, strpos($imageData, ",")+1);

    $unencodedData=base64_decode($filteredData);
    $fp = fopen( 'test.png', 'wb' );
    fwrite( $fp, $unencodedData);
    fclose( $fp );
        echo "saved";
}
  else{

  echo "no raw data";
  }

在执行这个codeI有一个零大小PNG文件的图像?请告诉我与我的code中的问题?

When executing this code i got a zero size png file image? Whats the problem with my code?

推荐答案

我最近要做到这一点我自己。

I had to do this recently myself.

首先,我把我的canvasData成一个隐藏字段,并将其贴到我的PHP页面。

First I put my canvasData into a hidden field and posted it to my PHP page.

这回来格式为:数据:图像/ PNG; BASE64,iVBORw0 ......

您需要先起来分裂数据,因为这样:数据:图像/ PNG; BASE64,的头信息。剩下的就是EN codeD数据。

You need to split the data up first, as this: data:image/png;base64, is header information. The rest is the encoded data.

$rawData = $_POST['imageData'];
$filteredData = explode(',', $rawData);

$unencoded = base64_decode($filteredData[1]);

我然后我的服务器上创建映像:

I then create the image on my server:

//Create the image 
$fp = fopen('sigs/test1.png', 'w');
fwrite($fp, $unencoded);
fclose($fp); 

,然后读它做任何我想做的事情。

And then read it to do whatever I want with it.

$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);

我更相信有一个更优雅的解决这一问题,但是一直为我工作!

I'm more than sure there is a much more elegant solution to this, but this has been working for me!

检查本作的详细信息(可能):<一href="http://stackoverflow.com/questions/13751555/how-can-i-save-a-dynamically-generated-image-to-my-database">My自己的问题

Check this for more info (possibly): My own question

这篇关于如何挽救canvas标签图像PHP服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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