Node.js将图像导入内存并显示它
我正在制作一个Node.js/Electron应用程序,用于下载和显示图像。我正在使用请求从internet下载图像。我想将此图像保存在内存中并显示它,而不将文件保存在本地硬盘上。我知道我可以通过在DOM中插入Node.js将图像导入内存并显示它,node.js,Node.js,我正在制作一个Node.js/Electron应用程序,用于下载和显示图像。我正在使用请求从internet下载图像。我想将此图像保存在内存中并显示它,而不将文件保存在本地硬盘上。我知道我可以通过在DOM中插入来完成我的要求,但这是我代码的一个高度简化的版本,我试图完成的事情无法用它来完成 var image = fs.createWriteStream(?); // Is there anyway to save the image to memory? request(url).pipe(i
来完成我的要求,但这是我代码的一个高度简化的版本,我试图完成的事情无法用它来完成
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)
})