Get image as buffer from URL

12,323

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);
    }
});
Share:
12,323
Ihab
Author by

Ihab

Updated on June 14, 2022

Comments

  • Ihab
    Ihab almost 2 years

    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?

    • DanilGholtsman
      DanilGholtsman about 6 years
      what about converting image to base64 and then pass the data you get by chunks?
    • Ihab
      Ihab about 6 years
      do you mean like reading the base64 at the browser ? you will get CORS error, the images are not within our domain
  • Ihab
    Ihab about 6 years
    the options did the trick ! i was so naive thinking it should work simply by passing a URL .. Thanks Terry