gpt4 book ai didi

Node.js 将图像通过管道传输到内存中并显示它

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:33 28 4
gpt4 key购买 nike

我正在制作一个下载和显示图像的 Node.js/Electron 应用程序。我正在使用请求从互联网下载图像。我想将此图像保存在内存中并显示它,而不将文件保存在本地硬盘上。我知道我可以通过插入 <img src="url"> 来完成我在这里提出的要求。到 DOM 中,但这是我的代码的高度简化版本,我无法用它来完成我想要完成的任务。

var image = fs.createWriteStream(?); // Is there anyway to save the image to memory?
request(url).pipe(image);
$('img').exampleScriptToSetImage(image); // And is there any way to display that image in a element without saving it to the local disk and loading its path?

最佳答案

确实!您可以将请求的图像数据通过管道传输到 concat 流中,将缓冲区转换为 Base64,并将 Base64 编码设置为图像源。

var path = require('path')
var request = require('request') // or hyperquest, simple-get, etc...
var concat = require('concat-stream')

var image = request(url)
image.pipe(concat({ encoding: 'buffer' }, function (buf) {
var ext = path.extname(file.name).slice(1) // assuming you have the file name
if (ext === 'svg') ext = 'svg+xml'
var src = 'data:image/' + ext + ';base64,' + buf.toString('base64')
var img = document.createElement('img')
img.src = src
document.body.appendChild(img)
})

关于Node.js 将图像通过管道传输到内存中并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305436/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com