NodeJS: How To Create An RGBA PNG or TGA in Javascript / PNGJS

750 Views Asked by At

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?

0

There are 0 best solutions below