AskYous
AskYous

Reputation: 4760

Save binary image to file

I make an API request which returns a binary image. How can I save it to a file like photo.png on my machine? Doing some research, I've tried the following but when I open the image, my machine says it's damaged:

const buffer = new Buffer(imageBinary);
const b64 = buffer.toString("base64");
const path = `temp/${userId}`;
const url = path + "/photo.png";
if (!fs.existsSync(path)) fs.mkdirSync(path);
if (fs.existsSync(url)) fs.unlinkSync(url)
fs.createWriteStream(url).write(b64);
return url;

Edit: Here is the binary data FYI: https://gist.github.com/AskYous/1fd26dc0eb02b4ec1672dcf5c61a34df

Upvotes: 0

Views: 226

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136525

You do not need to re-encode the buffer as base64. Just write the binary buffer as is:

fs.createWriteStream(url).write(imageBinary);

Upvotes: 2

Related Questions