我正在制作一个下载和显示图像的 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)
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)