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.
Here is node.js code:
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.
The HTML File is :
<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.
Have you checked the info.buffer? is it coming properly? Can you try adding onload.
var image = new Image();
image.src = "data:image/jpeg;base64,"+info.buffer;
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.