Display image from blob using javascript and websockets

后端 未结 6 1363
春和景丽
春和景丽 2020-11-29 22:05

I\'m currently working on a WebSocket application that is displaying images send by a C++ server. I\'ve seen a couple of topics around there but I can\'t seem to get rid of

6条回答
  •  眼角桃花
    2020-11-29 22:27

    Thanks, it's working great!!

    So I figure I'd share my final javascript code:

    var socket = new WebSocket('ws://'+host+':'+port, protocol);
    socket.binaryType = 'arraybuffer';
    
    try {
        socket.onopen = function() {
            document.getElementById('status').style.backgroundColor = '#40ff40';
            document.getElementById('status').textContent = 'Connection opened';
        }
    
        socket.onmessage = function(msg) {
            var arrayBuffer = msg.data;
            var bytes = new Uint8Array(arrayBuffer);
    
            var image = document.getElementById('image');
            image.src = 'data:image/png;base64,'+encode(bytes);
        }
    
        socket.onclose = function(){
            document.getElementById('status').style.backgroundColor = '#ff4040';
            document.getElementById('status').textContent = 'Connection closed';
        }
    } catch(exception) {
        alert('Error:'+exception);
    }
    

    don't really understand why the blob version is so tricky but this did the trick!

提交回复
热议问题