我正在尝试获取画布数据并将其另存为png文件。我使用以下ajax代码并继续获取已保存的图像但图像已损坏。也许我有错误的$ _REQUEST属性?
感谢任何帮助。
var dataURL = canvas.toDataURL('image/png');
var imageURL;
$.ajax({
url: "saveimage.php",
type: 'POST',
dataType: 'json',
data: { 'data_url': dataURL },
complete: function(xhr, textStatus) {
// Request complete.
},
// Request was successful.
success: function(response, textStatus, xhr) {
console.log('Response: ', response);
// Conversion successful.
if (response.status_code === 200) {
imageURL = response.data.image_url;
// Paste the PNG image url into the input field.
document.querySelector('img').src = imageURL;
}
},
error: function(xhr, textStatus, errorThrown) {
// Some error occured.
console.log('Error: ', errorThrown);
}
});
}
<?php
file_put_contents('images/'. rand().'.png', base64_decode($_REQUEST['data_url']));
?>
答案 0 :(得分:2)
事实证明,这样做的方法是将数据分开,因为datatoURL实际上包含的信息多于我们对图像所需的信息。这段代码对我有用,希望它也可以帮助别人:
<?php
$data = $_REQUEST['data_url'];
list($t, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$filename='images/'. rand().'.png';
file_put_contents($filename, $data);
$response = array("image_url"=>$filename,"status_code"=>200);
echo json_encode($response);
?>