Node.js base64 encode a downloaded image for use in data URI

后端 未结 3 745
谎友^
谎友^ 2020-12-08 22:03

Using Node v0.2.0 I am trying to fetch an image from a server, convert it into a base64 string and then embed it on the page in an image tag. I have the following code:

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 22:56

    This works for me using request:

    const url = 'http://host/image.png';
    request.get({url : url, encoding: null}, (err, res, body) => {
        if (!err) {
            const type = res.headers["content-type"];
            const prefix = "data:" + type + ";base64,";
            const base64 = body.toString('base64');
            const dataUri = prefix + base64;
        }
    });
    

    No need for any intermediate buffers. The key is to set encoding to null.

提交回复
热议问题