简体   繁体   中英

Byte array into an image Node.js

I have a long array of bytes, with numbers from 0 to 255, and I know it's an image, so how can I save it like a file? I have tried a lot of things, but not success.
The image is created but won't open because it's damaged.

File .js

function saveImage(filename, data){
  //Data = [1,6,2,23,255,etc]
  var wstream = fs.createWriteStream(ARTWORK_PATH+filename);
   for (var i = 0; i < data.length; i++) {
       wstream.write(data[i].toString('base64'));
   }
   wstream.end();
}

Why use base64 encoding? If your image data in the data parameter as binary, you can write it.

fs.writeFile(filename, data,  "binary", function(){...});

I solved it doing this!

It was as simple as use a buffer...

function saveImage(filename, data){
  var myBuffer = new Buffer(data.length);
  for (var i = 0; i < data.length; i++) {
      myBuffer[i] = data[i];
  }
  fs.writeFile(ARTWORK_PATH+filename, myBuffer, function(err) {
      if(err) {
          console.log(err);
      } else {
          console.log("The file was saved!");
      }
  });
}
saveImage("image.jpg", [0,43,255,etc]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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