Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

node.js - Socket.io began to support binary stream from 1.0, is there a complete example especially for image

I'm a beginner on node.js and socket.io. Socket.io began to support binary stream from 1.0, is there a complete example especially for image push to client and show in canvas? thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is a bit complicated but should work in Chrome, Firefox, and IE10+ (not sure about Opera and Safari):

Somewhere on the server-side:

io.on('connection', function(socket){
    fs.readFile('/path/to/image.png', function(err, buffer){
        socket.emit('image', { buffer: buffer });
    });
});

And here is how you handle it on a client:

socket.on('image', function(data) {
    var uint8Arr = new Uint8Array(data.buffer);
    var binary = '';
    for (var i = 0; i < uint8Arr.length; i++) {
        binary += String.fromCharCode(uint8Arr[i]);
    }
    var base64String = window.btoa(binary);

    var img = new Image();
    img.onload = function() {
        var canvas = document.getElementById('yourCanvasId');
        var ctx = canvas.getContext('2d');
        var x = 0, y = 0;
        ctx.drawImage(this, x, y);
    }
    img.src = 'data:image/png;base64,' + base64String;
});

Just replace yourCanvasId with your canvas id :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...