(对不起我的英语)嗨,我有一个用 nodejs 创建的应用程序,用于将图像数据推送到网页中。
使用 socket.io 将来自 nodejs 服务器的数据推送到网页中
该数据是完整的图像,我尝试写入磁盘以查看图像并且很好。将数据放入缓冲区以在 base64 中编码,然后发送到网页,我尝试使用 'data:image/png;base64,'+data 显示,但没有发生任何事情......数据似乎是“完整的”,包括PNG图像的标题。
服务器使用 thrift 与另一个客户端(在 C++ 中)通信,该客户端创建图像并发送到 nodejs-thrift 服务器,当接收到图像时,nodejs-socket.io 服务器推送到网页。
一些代码:服务器端
var http = require('http'),
url = require('url'),
fs = require('fs'),
sys = require('sys');
var hserver = http.createServer(function(request,response){
var path = url.parse(request.url).pathname;
switch(path){
case '/':
fs.readFile(__dirname + '/index.html',function(err,data){
if(err) return send404(res);
response.writeHead(200,{'Content-Type':'text/html'});
response.write(data,'utf8');
response.end();
});
break;
default: send404(response);
}
}),
send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
};
hserver.listen(8080);
var io = require('socket.io');
var socket = io.listen(hserver);
//this is the function in the Thrift part to send the image data to webpage using socket.io
var receiveImage = function(image,success){
buff= new Buffer(image.data.toString('base64'),'base64');
socket.broadcast({
data: buff.toString('base64'),
width: image.width,
height: image.height
});
success(true);
}
在网页中,我尝试使用 socket.io 的 on.message 回调加载图像
<script>
var socket = new io.Socket(null,{port:8080});
socket.connect();
socket.on('message',function(obj){
document.getElementById('imagenes').src='data:image/png;base64,'+obj.data.toString();
});
socket.on('connect',function(){
document.getElementById('stream').innerHTML = "Conectado!"
});
</script>
但我看不到图像.. obj.data.toString('base64') 创建一个这样的字符串:
PNGIHDRKIDATxYw5L1LlFMM/migzWUadOadLUd+43PIfPU9VU5AJAg3dIWUmHAMajS8GUuq ............
.............
/NIlWDHUDmIPdHIEND
是图像的所有数据..
我怎样才能显示图像?(也许使用 img 标签或进入画布)
提前致谢。
编辑:对代码进行了一些更改,但没有任何改变..我的猜测..图像不显示,因为数据(PNGIHDRKIDATxYw......PdHIENDB)不是正确的数据..我搜索这个和 png用于显示内联图像的数据是不同的(没有标题 PNGIHDRKIDAT 和尾部ENDB),我删除了标题和尾部并且不显示..也许我收到的数据不正确,但如果我尝试写入文件系统在使用nodejs(fs)的服务器端,我使用二进制编码获得正确的图像(使用 fs.writeFileSync("imagen.png",image.data.toString('binary'),'binary') ),但使用base64编码没有图像。