0

I am populating 'imageData', applying it to a canvas, and then need to save it as a RGBA 16 or 32 bit image from Javascript.

// Set all the alpha values to max.
for (let i = 0; i < 64 * 64; i++){
    imageData.data[(i * 4) + 3] = 255;
}
ctx.putImageData(imageData, 0, 0);

I can save this to a PNG image like this:

const buf = await BufferWrapper.fromCanvas(canvasFull, 'image/png');
await buf.writeToFile(tilePath);

But the result is an RGB png image missing the Alpha Channel. I tried to use https://www.npmjs.com/package/pngjs to save the image:

var png = new PNG({ width: 1024, height: 1024, filterType: 4 }).parse(canvasFull.imageData, function (error, data) {
    console.log(error, data);
});
png.pack().pipe(fs.createWriteStream(tilePath));

But this only makes a black image, which again is missing the Alpha channel. How can I save an RGBA PNG or TGA image from Javascript?

Selzier
  • 101
  • 1
  • 6
  • 19
  • 1
    Is this running in nodejs or on a user's browser? – CRice May 29 '20 at 18:19
  • This is using NodeJS – Selzier May 29 '20 at 18:22
  • 1
    `fs.writeFile("image.png", new Buffer(canvas.toDataUrl().replace("data:image/png;base64,", ""), "base64"))` – CRice May 29 '20 at 18:27
  • Thanks! I tried this and it created a PNG but when opening in Photoshop there is only RGB channels, the Alpha Channel is missing- no RBGA – Selzier May 29 '20 at 19:08
  • Well I'm not sure in that case. But here's a thought, I notice in your example, the alpha is always set to 255 which is fully opaque. A png where every pixel has 255 alpha is equivalent to the same png without the alpha channel. Perhaps the image is being automatically compressed to remove the channel since in this situation it is not needed. Can you clarify if you are testing with an image that actually has some transparency or if all pixels are opaque like what you have in your example? – CRice May 29 '20 at 19:31

0 Answers0