我有以下代码,用于从方程式编辑器创建图像并单击保存按钮将其显示在画布中 显示后,我想保存它 它显示正常,但保存空白图像 请让我知道我要去哪里了
JavaScript代码
btn_save.onclick = function()
{
var canvasimg = document.getElementById("canvas");
var eq = document.getElementById("equation");
var context = canvasimg.getContext("2d");
var imgurl;
context.clearRect(0, 0, canvasimg.width, canvasimg.height);
context.drawImage(eq, 0, 0, 50, 50);
imgurl = canvasimg.toDataURL("image/png");
imgurl = encodeURIComponent(imgurl);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://www.build-exam.com/imgsave.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(imgurl);
}
PHP代码
<?php
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input"); // to get POST data
if($postdata)
{
print_r("came in postdata");
// Get the data
$imageData=$postdata;
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// $unencodedData= $imageData;
$filteredData = str_replace(' ', '+', $filteredData);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'd:\\Apache2.4\\htdocs\\imgfile.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
答案 0 :(得分:0)
在处理数据之前先对其解码,不要在base64中手动替换数据。
<?php
header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input"); // to get POST data
if($postdata)
{
// print_r("came in postdata");
// Get the data
$imageData = urldecode( $postdata );
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// $unencodedData= $imageData;
// $filteredData = str_replace(' ', '+', $filteredData);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
// echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'd:\\Apache2.4\\htdocs\\imgfile.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>