how to load an image from url into buffer in nodejs

前端 未结 5 934
谎友^
谎友^ 2020-12-29 19:31

I am new to nodejs and am trying to set up a server where i get the exif information from an image. My images are on S3 so I want to be able to just pass in the s3 url as a

相关标签:
5条回答
  • 2020-12-29 20:17

    Use the request library.

    request('<s3imageurl>', function(err, response, buffer) {
        // Do something
    });
    

    Also, node-image-headers might be of interest to you. It sounds like it takes a stream, so it might not even have to download the full image from S3 in order to process the headers.

    Updated with correct callback signature.

    0 讨论(0)
  • 2020-12-29 20:20

    Try setting up request like this:

    var request = require('request').defaults({ encoding: null });
    request.get(s3Url, function (err, res, body) {
          //process exif here
    });
    

    Setting encoding to null will cause request to output a buffer instead of a string.

    0 讨论(0)
  • 2020-12-29 20:22

    Use the axios:

    const response = await axios.get(url,  { responseType: 'arraybuffer' })
    const buffer = Buffer.from(response.data, "utf-8")
    
    0 讨论(0)
  • 2020-12-29 20:34

    I was able to solve this only after reading that encoding: null is required and providing it as an parameter to request.

    This will download the image from url and produce a buffer with the image data.

    Using the request library -

    const request = require('request');
    
    let url = 'http://website.com/image.png';
    request({ url, encoding: null }, (err, resp, buffer) => {
         // Use the buffer
         // buffer contains the image data
         // typeof buffer === 'object'
    });
    

    Note: omitting the encoding: null will result in an unusable string and not in a buffer. Buffer.from won't work correctly too.

    This was tested with Node 8

    0 讨论(0)
  • 2020-12-29 20:34

    request is deprecated and should be avoided if possible.

    Good alternatives include got (only for node.js) and axios (which also support browsers).

    Example of got:

    npm install got
    

    Using the async/await syntax:

    const got = require('got');
    
    const url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
    
    (async () => {
        try {
            const response = await got(url, { responseType: 'buffer' });
            const buffer = response.body;
        } catch (error) {
            console.log(error.body);
        }
    })();
    
    0 讨论(0)
提交回复
热议问题