如何挽救canvas标签图像PHP服务器?图像、标签、服务器、canvas

2023-09-10 13:32:19 作者:有個傻瓜曾經愛過妳

我有一个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",'https://m.xsw88.com/allimgs/daicuo/20230910/108.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!

检查本作的详细信息(可能):My自己的问题

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