在节点中没有 canvas 或 XMLHttpRequest 的情况下将图像 URL 转换为 base 64

Convert image URL to base 64 without canvas or XMLHttpRequest in node

我处于 slackbot 的上下文中,所以我不能使用 Canvas / XMLHttpRequest,只能使用简单的 request 我从这个要点中启发了自己:https://gist.github.com/oliyh/db3d1a582aefe6d8fee9

到目前为止我有这个:

function toDataURL(url) {
  request(url, function (error, response, body) {
    var b64 = Base64.encode(response);
    console.log(b64)
    return b64;
  });
}

我这样称呼它:

Buffer.from(toDataURL(`http://cos-work-spot/files/${ppl.image}`))

但我一直收到这个

 TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
     at Function.Buffer.from (buffer.js:183:11)
     at MergeMapSubscriber.getLdapUserBySlackId.concatMap [as project] (/mnt/space/root/workspace/ul- 
     butler-george/src/index.js:213:37)
     at <anonymous>
     at process._tickCallback (internal/process/next_tick.js:189:7)

在将其标记为重复之前,请记住我不能使用 Canvas / XMLHttpRequest!

您可以指定 null 的编码以使请求 return 成为 Buffer 对象。一旦我们有了图像缓冲区,我们就可以使用 .toString('base64');

得到一个 base64 字符串

我正在使用 request-promise-native 库来允许我使用基于承诺的方法(我认为它更容易阅读):

const rp = require('request-promise-native');

async function imageUrlToBase64(url) {
    const options = { url, encoding: null } // We specify a null encoding to return a buffer.
    let result = await rp(options); // Download the image buffer
    return result.toString('base64'); // Encode the buffer as a base64 string.
};

async function testUrlToBase64(url) {
    const base64 = await imageUrlToBase64(url);
    console.log("Base64 length:", base64.length);
    console.log("Base64 (first 100):", base64.substring(0,100));
}

// Image url.
const 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"

testUrlToBase64(url);