Malvrok Malvrok - 1 month ago 5
Javascript Question

Cant parse Buffered Byte Array into Image in Browser

Im trying to create an image from a buffered byte array. This is because im sending the image from the server to the client with json. Here's the code:

The client side is represented with the index.html file.

// index.html

<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 also tried what is inside the comments, but couldnt achieve it...

The server is represented with 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");
});

});


It's just a simple question, but I already search in the forum, but couldnt solve my problem. I'd appreciate if someone could help me, thanks!

Answer

This will work:

function _arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
}

socket.onmessage = function (event) {
    var json = JSON.parse(event.data);
    if (json.task == "display-image") {
        var imageUrl = _arrayBufferToBase64(json.data.data);
        document.querySelector("#ItemPreview").src = "data:image/png;base64," + imageUrl;
        var message = JSON.stringify({"task": "get-image", "data": ""});
        socket.send(message);
    }
};
Comments