在堆栈溢出的不同链接的帮助下,我遇到了以下代码。感谢您的每一个环节。但是我无法在HTML页面中显示图像。
这是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.
});
});
我将Test.jpeg保存在上述文件所在的文件夹中。
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>
注意:另外,Test.jpg的大小为1280 * 720.
答案 0 :(得分:0)
你检查过info.buffer吗?它来得好吗?你能尝试添加onload吗?
var image = new Image();
image.src = "data:image/jpeg;base64,"+info.buffer;
image.onload = function() {
ctx.drawImage(image, 0, 0);
};