从URL获取图像作为缓冲区

时间:2018-03-22 05:57:07

标签: javascript node.js request

我花了几个小时试图将图像数据作为缓冲区,搜索结果引导我使用" request"模块,其他建议导致在更高版本的节点中使用其他模块,我无法使用,因为到目前为止我们依赖于节点v 6.11。

以下是我的试验:

request(imageURL).pipe(fs.createWriteStream('downloaded-img-
1.jpg')).on('close', function () {
        console.log('ok');
});

request(imageURL, function (err, message, response) {
fs.writeFile('downloaded-img-2.jpg', response, 'binary', function (err) {
    console.log('File saved.');
});

fs.writeFile('downloaded-img-3.jpg', chunks, 'binary', function (err) {
        console.log('File saved.');
})

resolve(response);
})
.on('data', function (chunk) {
    chunks.push(chunk);
})
.on('response', function (response) {

});
});

"下载-img-1.jpg"正确下载,但我必须避免将文件保存在磁盘上,然后将其作为流读取,它是一个PRD环境约束。因此,下一个选项是使用图像数据,如#34;下载-img-2.jpg"和"下载-img-3.jpg",等待"响应"或者手工制作的"块",问题是这2张图片总是被破坏了,我不知道为什么?

所有这一切背后的重点是什么?我试图在URL文件中添加URL后面的图像,我使用的zip库(js-zip)接受缓冲区作为输入。任何想法,为什么我没有得到" chunks"或者#34;响应"正确?

1 个答案:

答案 0 :(得分:1)

我在节点6.9.2中测试了下面的代码,它会将图像下载为缓冲区。我还将缓冲区写入文件(只是为了测试一切正常!),body对象是一个包含图像数据的缓冲区:

"use strict";

var request = require('request');
var fs = require('fs');

var options = {
    url: "https://upload.wikimedia.org/wikipedia/commons/thumb/5/52/Hubble2005-01-barred-spiral-galaxy-NGC1300.jpg/1920px-Hubble2005-01-barred-spiral-galaxy-NGC1300.jpg",
    method: "get",
    encoding: null
};

console.log('Requesting image..');
request(options, function (error, response, body) {

    if (error) {
        console.error('error:', error);
    } else {
        console.log('Response: StatusCode:', response && response.statusCode);
        console.log('Response: Body: Length: %d. Is buffer: %s', body.length, (body instanceof Buffer));
        fs.writeFileSync('test.jpg', body);
    }
});