将字节数组转换为图像 Node.js

2022-01-21 00:00:00 image byte node.js base64 javascript

我有一个很长的字节数组,数字从 0 到 255,而且我知道它是一个图像,所以 我怎样才能像文件一样保存它? 我尝试了很多东西,但没有成功.
图像已创建但无法打开,因为它已损坏.

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

推荐答案

我解决了这个问题!

就像使用缓冲区一样简单...

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

相关文章