Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 720
user1364297 Avatar asked Jan 27 '15 16:01

user1364297


People also ask

How do I send a picture through WebSocket?

You can either combine websocket.py into your python server and use send_frames directly, or add framing to your 'protocol'. If the only thing you are sending in PNG images, you could parse the length out. Otherwise, you'll have to add your own framing from the python server.

Can WebSockets send and receive at the same time?

The key word in that definition is two-way: with WebSocket, both the client and the server can trigger communication with one another, and both can send messages, at the same time.

Why you should not use WebSocket?

Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.

What can be sent over WebSocket?

Sending Messages With WebSocket You can send both text and binary data through a WebSocket. For your demo application you need to send the contents of the textarea to the server when the form is submitted. To do this you first need to set up an event listener on the form.


1 Answers

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;
}
like image 198
Musa Avatar answered Oct 03 '22 11:10

Musa