Java AWT image alpha channel saving problem

Hey guys, I’m using an RGBA image for a terrain mixmap, where each channel corresponds to the opacity of a separate terrain texture (so I can blend multiple textures).

The problem is, if I save any pixel with no alpha, for example. RGBA (255,0,0,0) or (20,60,100,0) or (0,200,30,0) it just saves a blank pixel because the alpha component is zero. How can I fix this?


BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); //create image
//loop through and set pixels, which come from a bytebuffer which has perfectly fine data in it
for(int x = 0; x < width; x++)
{
	for(int y = 0; y < height; y++)
	{
		int i = (x + (width * y)) * 4;
				
		int r = buffer.get(i) & 0xFF;
		int g = buffer.get(i + 1) & 0xFF;
		int b = buffer.get(i + 2) & 0xFF;
		int a = buffer.get(i + 3) & 0xFF; //if i set this to 255 it 'partially works' but then the alpha channel values can't be used
		int c = (a << 24) | (r << 16) | (g << 8) | b;
		image.setRGB(x, y, c);
		}
	}
}
ImageIO.write(image, "PNG", filename); //save image

I could just save/load my bytebuffer to/from a file but i’d rather save them as images.

Thanks,
roland

You mean that saving color 255, 0, 0, 0 results with a color 0, 0, 0, 0 ?

Yeah ???

AWT is saving the data as premultiplied-with-alpha I’ll guess. Try coercing the data to not-premultiplied. I recall having some issue with this a few years ago… might even have been a bug in the png writer.

Cas :slight_smile:

Thanks, I thought that might be the case, but I tried using both BufferedImage.TYPE_INT_ARGB and BufferedImage.TYPE_INT_ARGB_PRE (where I both load and save the image) and they didn’t make a difference. I hope it’s not a bug :frowning: I can try a different PNG library to save the image I guess.

I think it might be a bug then. Fairly sure I had some severe headscratching over this exact issue.

Cas :slight_smile:

Hmm, I tried another library too (pngj) and no luck there. I guess I’ll just save it as a compressed byte array.
Thanks,
roland

Hmm actually how are you checking the output data?

Cas :slight_smile:

Opening it with gimp and deleting the alpha channel. Don’t know if that works though.

Saved as a compressed byte array now (with width and height stored in the first 8 bytes) and that works fine so I could just keep it like that, file size seems ok