Writing indexed PNG using Image IO

I’m trying to save this image to disk in correct format but not able to find the correct way of doing it in Java2D and using ImageIO to write the image to disk.

If you have used photoshop you can use “save for web…” and save image as PNG24 or PNG8. I want to save it as PNG8 so that the output image looks like this:

http://gamadu.com/temp/epg/example1.png

and not like this:

http://gamadu.com/temp/epg/example2.png

I do not want translucency. I want translucent pixels to have a black matte.

Here’s roughly what I am currently doing:

BufferedImage image= new BufferedImage(width, height, BufferedImage.BITMASK);
// do image editing.
// flush.
ImageIO.write(image, "PNG", targetImageFile);

This however saves the image as translucent, although BITMASK clearly states that transparency is either 1 or 0.

So, I tried to use BufferedImage.TYPE_BYTE_INDEXED, but the problem with that is that the background color ends up black and not transparent!

What’s the right way to create and save an image as PNG8?

BufferedImage.BITMASK won’t work, as it’s actually Transparency.BITMASK so is not an intended input for the BufferedImage constructor. (oh to retrofit the existing APIs with enums ><)

As for TYPE_BYTE_INDEXED; that’s the correct image type - but if you are constructing it with the basic constructor (not supplying a ColorModel) you’ll get one created for you that will be inappropriate (and no transparency colour).
As per the javadoc:

You’ll need to construct a TYPE_BYTE_INDEXED and supply it an IndexColorModel with a palette appropriate for the image you are converting.

Don’t ask me how you go about optimally reducing the number of colors in a 24bit png down to a 8bit palette - never had to do it myself :slight_smile:

Ok, so I have to provide for the color palette myself. :-X ::slight_smile:

Fine, I’ll cook something up.

Thanks.

Yeah it’s supposed to be Transparency.BITMASK
I made that mistake before too… it’s just stupid

Ok, got it working, here’s how it’s done:


final int[] colourMap = {   0x00000000, 0xff000000, 0xffffffff, 0xff353535, 0xff888888, 0xff969696, 0xff237fe9, 0xffff0000 };
IndexColorModel colorModel = new IndexColorModel(8, colourMap.length, colourMap, 0, true, 0, DataBuffer.TYPE_BYTE );
BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_BYTE_INDEXED, colorModel);

// Do whatever with your image 
// ...
ImageIO.write(image, "PNG", imageFile);

Offtopic: to prevent the syntax-highlighter from screwing up, start your multi-line comments with /** instead of /* :emo: (javadoc style)

Cleaned it up.