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:
and not like this:
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);
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:
Represents an indexed byte image. When this type is used as the imageType argument to the BufferedImage constructor that takes an imageType argument but no ColorModel argument, an IndexColorModel is created with a 256-color 6/6/6 color cube palette with the rest of the colors from 216-255 populated by grayscale values in the default sRGB ColorSpace.
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