javascript - 如何在 NodeJS 中显示图像而不从 url 下载图像?

标签 javascript node.js node-fetch

在 NodeJS 中,我使用了名为 node-fetch 的包,也用于获取 JSON 响应,但是图像响应怎么样?我怎样才能做到这一点?在我当前的代码中,它只保存图像,而不像Python中的PIL那样显示。

var tr = "https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI"

export async function get_image() {
    const get_url = await fetch(tr)
    const image = get_url.body.pipe(fs.createWriteStream('./image.png'))
}

await get_image();

最佳答案

您可以使用 axios 获取 Base64 格式的图像并将其保存在变量中像这样的模块:

const axios = require('axios')
const imageURL = 'https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI';

(async ()=>{
    // Get image Buffer from url and convert to Base64
    const image = await axios.get(imageURL, {responseType: 'arraybuffer'});
    const base64Image = Buffer.from(image.data).toString('base64');

    // Do stuff with result...
    console.log(base64Image);
})();

// Or if you prefer, a one liner
(async ()=>{
    const base64Image = Buffer.from((await axios.get(imageURL, {responseType: 'arraybuffer'})).data).toString('base64');
})();

您可以使用网站decode the base64 string into an image来检查它是否有效。 .

关于javascript - 如何在 NodeJS 中显示图像而不从 url 下载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70912876/

相关文章:

javascript - 如何使用node-fetch从API获取数据和响应状态?

node.js - 如何使用 Node Fetch 将来自 HTTP 请求的数据保存在变量中?

javascript - 在初始化之前使用变量。 JS

javascript - 如何在警报框中插入单选按钮

javascript - 消防商店 : How to update Field in object data structure in firestore using cloud functions

javascript - 如何在CasperJS中顺序打开2个网页?

ios - Twilio客户端将自定义调用参数从nodejs服务器发送到ios客户端

node.js - Node 调用带有临时表的 postgres 函数导致 "memory leak"

javascript - 在 React 中使用 this.props.src 导入图像