Byte array into an image Node.js

眉间皱痕 提交于 2019-12-30 07:16:02

问题


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();
}

回答1:


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

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



回答2:


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]);


来源:https://stackoverflow.com/questions/40376410/byte-array-into-an-image-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!