透明背景png - Java - BufferedImage

时间:2013-03-27 18:18:19

标签: java bufferedimage

我正在尝试使用透明而不是白色背景的Java显示中的图像创建png。尝试在新颜色(0,0,0,0)中将alpha设置为0 - 背景仍然显示为白色?

我正在使用BufferedImage

            WritableRaster raster = onscreenImage.getRaster();
            WritableRaster newRaster;
            newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
            DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
            DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
                                                          cm.getRedMask(),
                                                          cm.getGreenMask(),
                                                          cm.getBlueMask());
            BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false,  null);
            try { ImageIO.write(rgbBuffer, suffix, file); }
            catch (IOException e) { e.printStackTrace(); }

1 个答案:

答案 0 :(得分:0)

您没有在颜色模型中指定alpha分量。试试这种方式:

newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, null);
DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
                                                      cm.getRedMask(),
                                                      cm.getGreenMask(),
                                                      cm.getBlueMask(),
                                                      cm.getAlphaMask());