Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create image from ArrayBuffer in Nodejs

I'm trying to create an image file from chunks of ArrayBuffers.

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

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

all.end();

where picarray contains ArrayBuffer chunks. However, I get the error
TypeError: Invalid non-string/buffer chunk.

How can I convert ArrayBuffer chunks into an image?

like image 520
Yaan Avatar asked Mar 25 '16 20:03

Yaan


Video Answer


2 Answers

Have you tried first converting it into a node.js. 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).

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();
like image 68
Nick Jennings Avatar answered Sep 28 '22 09:09

Nick Jennings


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.

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")
            }
        });
    });
};
like image 44
Sheelpriy Avatar answered Sep 28 '22 09:09

Sheelpriy