0

I have the following tensor in nodejs:

enter image description here

I then encode it to PNG like so:

const encodedTensor = await tf.node.encodePng(intTensor);

And pipe it to the frontend like this:

fs.writeFileSync("image.png", encodedTensor);
const readStream = fs.createReadStream('image.png');
readStream.pipe(res);

Finally, this is what shows up in my console:

enter image description here

What is this format? and how can I download the image on the client? Or is there any other way of converting the tensor to images in nodejs and then downloading it on the client?

Thank you

1 Answers1

0

It turns out that the ouptut in the console is a stringified/damaged version of uint8 array. It gets damaged while being sent from the server to client.

That's why instead of sending it as an int8 array I converted it to a buffer on the server, and then the buffer to a base64 string like so:

const encodedTensor = await tf.node.encodePng(tensor);

const data = Buffer.from(encodedTensor).toString("base64");
res.send(data);

After that I used this function to download the image on the client:

function downloadBase64File(contentType, base64Data, fileName) {
  const linkSource = `data:${contentType};base64,${base64Data}`;
  const downloadLink = document.createElement("a");
  downloadLink.href = linkSource;
  downloadLink.download = fileName;
  downloadLink.click();
}

downloadBase64File("image/png", response.data, "image.png");

Hope it helps someone.