nodejs使用axios获取url的图片信息并转换为base64

2 阅读1分钟

推荐一款AI网站, AI写作与AI绘画智能创作平台 - 海鲸AI | 智能AI助手,支持GPT4设计稿转代码

要使用axios库在Node.js中获取URL的图片信息并将其转换为Base64编码,首先需要安装axios。如果你还没有安装,可以使用以下命令来安装它:

npm install axios

安装完成后,你可以使用以下代码来获取图片并将其转换为Base64编码:

const axios = require('axios');
const fs = require('fs');

// URL of the image you want to fetch
const imageUrl = 'https://example.com/image.jpg';

axios({
  method: 'get',
  url: imageUrl,
  responseType: 'arraybuffer' // Important to get the image as a binary buffer
})
  .then((response) => {
    // Convert the Buffer to a Base64 string
    const base64Image = Buffer.from(response.data, 'binary').toString('base64');

    // Now you have the image in Base64, you can do what you need with it
    // For example, you could write it to a file
    fs.writeFile('image.base64', base64Image, (err) => {
      if (err) throw err;
      console.log('The file has been saved!');
    });

    // Or simply log the Base64 string
    console.log(base64Image);
  })
  .catch((error) => {
    console.error(error);
  });

在这段代码中,axios配置对象中的responseType属性被设置为'arraybuffer',这样axios就会以二进制形式接收数据。然后,使用Buffer.from方法将二进制数据转换为Buffer对象,并使用toString('base64')方法将其转换为Base64编码的字符串。

你可以将Base64字符串保存到文件中,或者根据你的需求进行其他操作。