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

news/2024/7/19 14:19:57 标签: nodejs, js, axios

推荐一款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字符串保存到文件中,或者根据你的需求进行其他操作。


http://www.niftyadmin.cn/n/5403739.html

相关文章

AzerothCore安装记录

尝试在FreeBSD系统下安装AzerothCore 首先安装相关软件 pkg install cmake mysql80-server boost-all装完mysql之后提示: MySQL80 has a default /usr/local/etc/mysql/my.cnf, remember to replace it with your own or set mysql_optfile"$YOUR_CNF_FILE i…

Java项目layui分页中文乱码

【问题描述】这部分没改之前中文乱码。 【解决办法】在layui.js或者layui.all.js文件中替换共、页、条转换成Unicode码格式。 字符Unicode共&#x5171页&#x9875条&#x6761【完美解决】改完之后重新运行项目,浏览器F12缓存清除就好了,右键

政务信息化项目可行性研究报

第四章 总体建设方案 1 建设原则 本项目将在借鉴国内相关项目建设成功经验的基础上,充分利用现有先进、 成熟技术,并考虑长远发展需求,予以统一规划、统一布局、统一设计、规范标 准、突出重点、分步实施。 (1)标准…

论文阅读_代码生成模型_CodeLlama

英文名称: Code Llama: Open Foundation Models for Code 中文名称: Code Llama:开放基础代码模型 链接: https://arxiv.org/abs/2308.12950 代码: https://github.com/facebookresearch/codellama 作者: Baptiste Rozire, Jonas Gehring, Fabian Gloeckle, Sten So…

【牛客】SQL132 每个题目和每份试卷被作答的人数和次数

描述 现有试卷作答记录表exam_record(uid用户ID, exam_id试卷ID, start_time开始作答时间, submit_time交卷时间, score得分): iduidexam_idstart_timesubmit_timescore1100190012021-09-01 09:01:012021-09-01 09:41:01812100290022021-09…

[electron]窗口 BrowserWindow

优雅的显示窗口 const {app, BrowserWindow} require(electron);function createMainwindow(){const mainwindow new BrowserWindow({x: 300,y: 400,width: 600,height: 600,});mainwindow.loadFile(index.html); }app.on(ready, ()>{createMainwindow(); });对于这样的代…

Qt 简约美观的加载动画 文本风格 第八季

今天和大家分享一个文本风格的加载动画, 有两类,其中一个可以设置文本内容和文本颜色,演示了两份. 共三个动画, 效果如下: 一共三个文件,可以直接编译 , 如果对您有所帮助的话 , 不要忘了点赞呢. //main.cpp #include "LoadingAnimWidget.h" #include <QApplic…

【UEFI实战】BIOS中的openssl

BIOS中的openssl openssl是一个密码库或者密码工具&#xff0c;在密码学基础_hex string is too short, padding with zero bytes t-CSDN博客介绍了基本的密码学概念已经openssl工具的使用&#xff0c;而这里将介绍BIOS下如何使用openssl。 在开源的BIOS代码库EDK中包含一个C…