Hello there! I am currently facing an issue while attempting to generate an image from a buffered byte array. The reason behind this is that I need to transfer the image from the server to the client using JSON. Below is the code snippet in question:
The index.html file represents the client side.
<img id="ItemPreview">
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(event){
setTimeout(function(){
var message = JSON.stringify({"task" : "initialize", "data" : ""});
socket.send(message);
}, 1000);
};
socket.onmessage = function(event){
var json = JSON.parse(event.data);
if(json.task == "display-image"){
console.log("From Client\t\t: " + json);
console.log(json.data.data);
var urlCreator = window.URL || window.webkitURL;
//var imageUrl = urlCreator.createObjectURL(json.data);
var imageUrl = urlCreator.createObjectURL(new Blob(json.data.data));
document.querySelector("#ItemPreview").src = imageUrl;
//document.querySelector("#ItemPreview").src = "data:image/png;base64," + json.data.data;
var message = JSON.stringify({ "task" : "get-image", "data" : ""});
socket.send(message);
}
};
</script>
I have also attempted what was mentioned in the comments, but unfortunately, I haven't been successful...
On the other hand, the server side is represented by the index.js file.
//index.js
var server = require('ws').Server;
var s = new server({ port : 8080 });
var fs = require('fs');
s.on('connection', function(ws){
ws.on('message', function(message){
var json = JSON.parse(message);
console.log("From Server:\t\t" + json);
if(json.task == "initialize"){
var image = fs.readFileSync("./img/1.jpg");
var messageToSend = JSON.stringify({
"task" : "display-image",
"data" : image
});
ws.send(messageToSend);
}
});
ws.on('close', function(){
console.log("I lost a client");
});
});
Although it may seem like a simple query, I have exhaustively searched through various resources online but to no avail. Any assistance or guidance on this matter would be greatly appreciated. Thank you in advance!