[英]emitting image from node.js with help of socket.io to html does not work
With the help of different links from stack overflow, i came across the below code. 在堆栈溢出的不同链接的帮助下,我遇到了以下代码。 Thanks for every link. 感谢您的每个链接。 But im unable to display image in the HTML Page. 但是我无法在HTML页面中显示图像。
Here is node.js code: 这是node.js代码:
socketio.listen(server).on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
fs.readFile(__dirname + '/Test.jpeg', function(err, buf) {
socket.emit ('image', { image: true, buffer: buf.toString('base64') });
}); // file reading.
});
});
I keep the Test.jpeg in the folder where the above file exists. 我将Test.jpeg保留在上述文件所在的文件夹中。
The HTML File is : HTML文件是:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<body>
<canvas id="myCanvas" width="280" height="220" style="border:1px solid #000000;">
</canvas>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<input type="text" id="outgoingChatMessage">
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
var ctx = document.getElementById('myCanvas').getContext('2d');
$(function(){
var iosocket = io.connect();
iosocket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
iosocket.on('message', function(message) {
$('#incomingChatMessages').append($('<li></li>').text(message));
});
iosocket.on('disconnect', function() {
$('#incomingChatMessages').append('<li>Disconnected</li>');
});
iosocket.on('image', function(info) {
$('#incomingChatMessages').append($('<li>image event..</li>'));
if ( info.image) {
var img = new Image();
img.src = 'data:image/jpeg;base64,' + info.buffer;
ctx.drawImage(img, 0, 0);
}
}); // image
});
$('#outgoingChatMessage').keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($('#outgoingChatMessage').val());
$('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val()));
$('#outgoingChatMessage').val('');
}
});
});
</script>
</head>
</html>
NOTE: Also, Test.jpg is 1280 * 720 in size. 注意:此外,Test.jpg的尺寸为1280 * 720。
Have you checked the info.buffer? 您检查过info.buffer吗? is it coming properly? 来得好吗? Can you try adding onload. 您可以尝试添加onload吗?
var image = new Image();
image.src = "data:image/jpeg;base64,"+info.buffer;
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.