5

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
  • It looks like you're writing the data to a file as a base64 encoded string. You need to save it in binary format for it to be opened as an image file. Commented Nov 2, 2016 at 9:31

2 Answers 2

2

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

fs.writeFile(filename, data,  "binary", function(){...});
Sign up to request clarification or add additional context in comments.

2 Comments

I tried that but still doesn't work, I also tried data.join() before writing it but nothing. The bytes array comes from this plugin jsmediatags, they have the next method to do it but does not work to me. var base64String = ""; for (var i = 0; i < image.data.length; i++) { base64String += String.fromCharCode(image.data[i]); } var dataUrl = "data:" + image.format + ";base64," + window.btoa(base64String);
what is wrong? maybe you can indentify your saved image first bytes. for example when you save a png file, the first bytes contains "PNG" string which you can read
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]);

1 Comment

I tried this, the image is creating but when I am trying to open the image file, its saying that 'photo viewer doesn't support this file format '

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.