如何从节点js下载图像并将其转换为二进制

How to download image from node js and convert it to binary

我在某个 url 有一张图片,例如“http://91.123.58.169:322/snapshot.cgi?user=admin&pwd=123456”。这是网络摄像机的当前帧。

我想将此图像下载到 node.js 服务器,将其转换为二进制文件并通过 socket.io

发送

解决我的问题的正确方法是什么?

好的,我自己写了代码,它可以工作。 所以,我们有网络摄像机图像框架。 我们通过http-request模块获取,然后将其保存到文件系统,然后通过socket.io

将编码为base64的图像发送给客户端
var httpRequest = require('http-request');
    socket.on('camera', function(data) {
            var options = { url: 'http://192.168.1.178:80/snapshot.cgi?user=admin&pwd=123456' };
            httpRequest.get(options, __dirname + '/camera.jpg', function(error, result) {
                if (error) {
                    console.error(error);
                } else {
                    fs.readFile(__dirname + '/camera.jpg', function(err, buf) {
                        socket.emit('camera', { image: true, buffer: buf.toString('base64') });
                    });
                }
            });
        });

同时在客户端:

socket.on('camera', function(data) {
    var image = new Image();
    image.src = 'data:image/jpeg;base64,' + data.buffer;

    var img = $("<img />").attr('src', image.src);
    $("#cameraDiv").empty();
    $("#cameraDiv").append(img);
    img.addClass("img-rounded img-responsive");
    img.css("width", "400px");
    img.css("height", "300px");
    img.css("margin-left", "auto");
    img.css("margin-right", "auto");
});