Creating transparent pixels in PNG/Buffered Image
Posted on 2006-05-28
I am attempting to write a small utility to scale 8-bit PNG files. However, when I write out the scaled image the transparent field is getting mapped to a color rather than transparency.
The basic method is very simple:
BufferedImage bi = ImageIO.read(srcFile) ;
Image scaled = bi.getScaledInstance(targetWidth, targetHeight, Image.SCALE_FAST) ;
ColorModel cm = bi.getColorModel() ;
BufferedImage out = toBufferedImage1(bi, scaled, cm) ;
ImageIO.write(out, "png", destFile);
the tricky part is converting the scaled image to a buffered image in order to write out the PNG.
I'm doing that like this:
// Option 1 -- Using the screen as basis for gc
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
// Option 2 - using the original image as basis for gc
Graphics2D originalG = original.createGraphics() ;
GraphicsConfiguration origDC = originalG.getDeviceConfiguration() ;
BufferedImage bimage = origDC.createCompatibleImage(image.getWidth(null), image.getHeight(null), Transparency.BITMASK);
and then copy the scaled image into the new buffered image like this:
Graphics g = bimage.createGraphics();
g.drawImage(image, 0, 0, null);
If I use option 1 (based on the screen) I get a 24-bit PNG that has correct transparency.
If I use option 2 (based on the original image) I get an 8-bit PNG that is correct except all transparent fields are filled with an arbitrary, incorrect color.
What I want is an 8-bit PNG with correct transparency.
So, can anyone tell me how to:
a) Create an 8-bit PNG in another way that preserves transparency?
or b) Tell me how to make a buffered 8-bit image fully transparent (before I paint over with the image data)? I've tried various calls to setRGB and calling writableRaster w/o success.
or c) Give me a different way to scale an 8-bit PNG?
Thanks in advance for any suggestions.