Byte array into an image Node.js
14,936
Solution 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(){...});
Solution 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]);
Author by
Eduardo Alfredo Hopperdietzel
Updated on June 04, 2022Comments
-
Eduardo Alfredo Hopperdietzel almost 2 years
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 .jsfunction 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(); }
-
tebs1200 over 7 yearsIt 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.
-
-
Eduardo Alfredo Hopperdietzel over 7 yearsI 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);
-
sarkiroka over 7 yearswhat 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
-
Venkatesh Voona about 5 yearsI 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 '