在 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/