Reputation:
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?
Upvotes: 1
Views: 4777
Reputation: 39496
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);
}
Upvotes: 2
Reputation: 6411
Try the following:
BufferedImage
.IndexColorModel
with the desired parameters.ColorConvertOp
. You can pass null
as the RenderingHints
argument.ColorConvertOp.createCompatibleDestImage
][3] to receive a new BufferedImage
instance (destination).ColorConvertOp.filter
][4] to perform the conversion from the source to the destination.I'm not completely sure about this, but the ColorConvertOp
seems like a good starting point. Tell us how it works out!
[3]: http://java.sun.com/javase/6/docs/api/java/awt/image/ColorConvertOp.html#createCompatibleDestImage(java.awt.image.BufferedImage, java.awt.image.ColorModel) [4]: http://java.sun.com/javase/6/docs/api/java/awt/image/ColorConvertOp.html#filter(java.awt.image.BufferedImage, java.awt.image.BufferedImage)
Upvotes: 0
Reputation: 25523
I don't know, but I'm sure the answer is in The png Specification. Hope this helps!
Isn't there a library for java for writing png files (java bindings for libpng perhaps?) that will do the hard work for you? (and probably save you many headaches when things don't quite work)
Upvotes: -1