如何从 Node.js 缓冲区显示 JPG 图像(UInt8Array)

2022-01-10 00:00:00 node.js electron javascript html

我有一个自定义 Node.JS 插件,它可以将 jpg 捕获传输到我的应用程序,它运行良好 - 如果我将缓冲区内容写入磁盘,它是一个正确的 jpg 图像,正如预期的那样.

I have a custom Node.JS addon that transfers a jpg capture to my application which is working great - if I write the buffer contents to disk, it's a proper jpg image, as expected.

var wstream = fs.createWriteStream(filename);
wstream.write(getImageResult.imagebuffer);
wstream.end();

我正在努力将该图像显示为 img.src 而不是将其保存到磁盘,例如

I'm struggling to display that image as an img.src rather than saving it to disk, something like

var image = document.createElement('img');
var b64encoded = btoa(String.fromCharCode.apply(null, getImageResult.imagebuffer));
image.src = 'data:image/jpeg;base64,' + b64encoded;

转换后 b64encoded 中的数据是正确的,因为我在 http://codebeautify 上进行了尝试.org/base64-to-image-converter 并显示正确的图像.我一定错过了一些愚蠢的东西.任何帮助都会很棒!

The data in b64encoded after the conversion IS correct, as I tried it on http://codebeautify.org/base64-to-image-converter and the correct image does show up. I must be missing something stupid. Any help would be amazing!

感谢您的帮助!

推荐答案

这就是你想要的吗?

// Buffer for the jpg data
var buf = getImageResult.imagebuffer;
// Create an HTML img tag
var imageElem = document.createElement('img');
// Just use the toString() method from your buffer instance
// to get date as base64 type
imageElem.src = 'data:image/jpeg;base64,' + buf.toString('base64');

相关文章