Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image as buffer from URL

I have spent couple of hours trying to get image data as a buffer, search results lead me to using "request" module, others suggestions lead to using other modules in higher version of node, which I cannot use because we depend on node v 6.11 so far.

Here are my trials:

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) {

});
});

The "downloaded-img-1.jpg" gets downloaded correctly, but I have to avoid saving the file on disk, then read it as a stream, it's a PRD environment constraint. So the next option is to use image data, as demonstrated by "downloaded-img-2.jpg" and "downloaded-img-3.jpg", by waiting for the "response" or the hand-made "chunks", the problem is that these 2 images are always corrupted, and I don't know why?

What is the point behind all of that? I am trying to add the image behind the URL in a zip file, and the zip lib I use (js-zip) accepts buffer as an input. Any ideas why I am not getting the "chunks" or the "response" correctly?

like image 574
Ihab Avatar asked Oct 17 '22 21:10

Ihab


1 Answers

I've tested the code below in Node 6.9.2, it will download an image as a buffer. I also write the buffer to a file (just to test all is OK!), the body object is a buffer containing the image data:

"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);
    }
});
like image 174
Terry Lennox Avatar answered Oct 19 '22 23:10

Terry Lennox