如何在服务器端保存PNG图像,使用base64数据字符串javascript


How to save a PNG image server-side, from a base64 data string javascript

我有这段代码,要么ajax没有正确传输数据,要么我的php工作不正常。我知道拉票正在保存到它写入页面的数据png中。有没有一种方法可以将其转换为文件并从javascript中保存?

启动JAVASCRIPT:------------------

<--获取拉票元素并转换为数据png-->

var canvas = document.getElementById("textCanvas"); 
var img = canvas.toDataURL("image/png");

<--结束拉票元素并转换为数据png-->

<--发送到php文件-->

var onmg = encodeURIComponent(img);
var xhr = new XMLHttpRequest();
var body = "img=" + onmg;
xhr.open('POST', "convertit.php",true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Length", body.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(body);
xhr.onreadystatechange = function () {
   if (xhr.status == 200 && xhr.readyState == 4) {
     document.getElementById("div").innerHTML = xhr.responseText;
   } else {
     document.getElementById("div").innerHTML = 'loading';
     }
   }

<--END发送到php文件-->

END JAVASCRIPT:------------------

启动PHP:------------------

$img = $_POST['img']; 
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents('/uploads/file.png', $data);

结束PHP:------------------

将php更改为-------->

define('UPLOAD_DIR', 'images/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . 'txtimg.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';

我从----->http://j-query.blogspot.com/2011/02/save-base64-encoded-canvas-image-to-png.html

-欢呼非常棒:)