我通過python連接到IP Cam並在Java servlet中運行該腳本。然後我使用Java加載每個圖像,並將其轉換爲具有base64編碼的字節數組。最後,我通過AJAX通過JSON對象請求這些數據。我沒有收到任何錯誤,但圖像也沒有出現。爲什麼我的圖像不會從我的java servlet加載?
的JavaScript:
$().ready(callToServer);
function callToServer(){
$.ajax({
type:"GET",
url:"DroneServlet.do",
async:true,
data: null,
dataType:"json",
success: drawImage,//function to do is success
error: badRequest//function to do is error
});
setTimeout(callToServer,5000);
}
function toArray(str){
var i;
var bytes=[];
for(i=0;i<str.length;i++)
{
bytes.push(str.charAt(i));
}
return bytes;
}
function badRequest(){
console.log("failed");
}
function drawImage(json)
{
var img = json.imgData[0].imageToDisplay;
var biStr=toArray(img);
var data = biStr.join('');
//var base64 = window.btoa(data);
document.getElementById("dynamic").src = "data:image/jpeg;base64," + data;
}
Java代碼片段:
byte[] imgData = PythonRunner.grabPhotoBytes();//loads single image and convert to byte[]
JSONObject jsonResponse = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject img = new JSONObject();
String encodedImg = Base64.encodeBase64String(imgData);
img.put("imageToDisplay", encodedImg);
jsonArray.add(img);
jsonResponse.put("imgData", jsonArray);
out.println(jsonResponse.toJSONString() ); // send the WeatherData collection in JSON format