sending a png image over a websocket and rendering the received image

user1364297 picture user1364297 · Jan 27, 2015 · Viewed 7.8k times · Source

On server: I am loading a png image:

var myimage = png.load('test.png');

then sending over websocket connection:
ws.send(myimage);

On client:

function onMessage(evt) {
    if (evt.data instanceof ArrayBuffer) {
        var length = evt.data.byteLength;
        var bytes = new Uint8Array(evt.data);
        var image = document.getElementById("image");
        var img = new Image();
        img.src = 'data:image/png;base64,'+ window.btoa(bytes);
        var ctx = image.getContext("2d");
        ctx.drawImage(img, 0, 0);
}

Not getting anything to display on canvas. Any ideas about what I'm doing incorrectly?

Answer

Musa picture Musa · Feb 1, 2015

Try creating a blob and converting that to a blob url

function onMessage(evt) {
    if (evt.data instanceof ArrayBuffer) {
        var length = evt.data.byteLength;
        var blob = new Blob([evt.data],{type:'image/png'});
        var url = URL.createObjectURL(blob);
        var image = document.getElementById("image");
        var img = new Image();
        img.onload = function(){
            var ctx = image.getContext("2d");
            ctx.drawImage(img, 0, 0);
        }
        img.src = url;
}