簡體   English   中英

將圖像從 canvas 保存到服務器。 空白圖像被保存

[英]Saving image from canvas to server. Blank image getting saved

我有以下代碼用於從方程式編輯器創建圖像並單擊保存按鈕將其顯示在 canvas 顯示后,我希望將其保存它顯示正常,但保存空白圖像請告訴我哪里出錯了

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 );
}
?>

只需在操作之前對數據進行解碼,不要手動替換 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 );
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM