简体   繁体   English

在 Nodejs 中从 ArrayBuffer 创建图像

[英]Create image from ArrayBuffer in Nodejs

I'm trying to create an image file from chunks of ArrayBuffers.我正在尝试从 ArrayBuffers 块创建图像文件。

all= fs.createWriteStream("out."+imgtype);

for(i=0; i<end; i++){
    all.write(picarray[i]);
}

all.end();

where picarray contains ArrayBuffer chunks.其中picarray包含 ArrayBuffer 块。 However, I get the error但是,我收到错误
TypeError: Invalid non-string/buffer chunk . TypeError: Invalid non-string/buffer chunk

How can I convert ArrayBuffer chunks into an image?如何将 ArrayBuffer 块转换为图像?

Have you tried first converting it into a node.js. 您是否尝试过将其转换为node.js. Buffer ? Buffer (this is the native node.js Buffer interface, whereas ArrayBuffer is the interface for the browser and not completely supported for node.js write operations). (这是本机node.js Buffer接口,而ArrayBuffer是浏览器的接口,而node.js写操作并不完全支持)。

Something along the line of this should help: 沿着这条路线的东西应该有所帮助:

all= fs.createWriteStream("out."+imgtype);

for(i=0; i<end; i++){
    var buffer = new Buffer( new Uint8Array(picarray[i]) );
    all.write(buffer);
}
all.end();

after spending some time i got this, it worked for me perfectly. 花了一些时间我得到了这个,它对我来说很完美。

as mentioned by @Nick you will have to convert buffer array you recieved from browser in to nodejs Buffer. 正如@Nick所提到的,你必须将从浏览器中收到的缓冲区数组转换为nodejs Buffer。

var readWriteFile = function (req) {
    var fs = require('fs');
        var data =  new Buffer(req);
        fs.writeFile('fileName.png', data, 'binary', function (err) {
            if (err) {
                console.log("There was an error writing the image")
            }
            else {
                console.log("The sheel file was written")
            }
        });
    });
};

Array Buffer is browser supported which will be unsupportable for writing file, we need to convert to Buffer native api of NodeJs runtime engine. Array Buffer 是浏​​览器支持的,不支持写入文件,我们需要转换成 NodeJs 运行时引擎的 Buffer 原生 api。

This few lines of code will create image.这几行代码将创建图像。

const fs = require('fs');
let data = arrayBuffer // you image stored on arrayBuffer variable;
data = Buffer.from(data);
fs.writeFile(`Assets/test.png`, data, err => { // Assets is a folder present in your root directory
      if (err) {
         console.log(err);
      } else {
         console.log('File created successfully!');
      }
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM