I am trying to create a transparent PNG image from a BufferedImage in Java.
The PNG will be loaded into another piece of the software, that does not support the alpha channel.
That should be fine, because, according to Chapter 8, section 5, part 4 of the PNG book, I can achieve transparency by specifying a pixel value to be transparent. This works by creating a tRNS
header in the png file.
I am unsure how to translate this technical detail to Java code. The actual image itself is monochrome; each pixel is going to be black or white. I would like to replace each white pixel with a transparent pixel, without using the alpha channel. May someone push me in the right direction please?
You can use the following code.
Create a monochrome and transparent BufferedImage:
public static BufferedImage createTransparentMonochromeBufferedImage(int w, int h)
{
// The color map contains the colors black and white
byte[] cMap = {0, 0, 0, (byte)255, (byte)255, (byte)255};
// Create an IndexColorModel setting white as the transparent color
IndexColorModel monochrome = new IndexColorModel(8, 2, cMap, 0, false, 1);
// Return a new BufferedImage using that color model
return new BufferedImage(w, h, BufferedImage.TYPE_BYTE_INDEXED, monochrome);
}
Save the BufferedImage in a PNG file:
public static void saveBufferedImageAsPNG(BufferedImage img, String filename)
throws IOException{
File file = new File(filename);
ImageIO.write(img, "png", file);
}