将JFrame保存为具有透明背景的图像

时间:2015-06-03 09:58:44

标签: java image swing transparency

对不起,我知道有很多这样的问题,但我无法找到解决方案。我尝试了不同的东西,但只是我不能让背景透明。这是我的测试代码:

public class Pngs extends JPanel {

public void paint(Graphics g) {
    Image img = createImage();
    g.drawImage(img, 0, 0, this);
}

public static BufferedImage getScreenShot(
        Component component) {

    BufferedImage image = new BufferedImage(
            component.getWidth(),
            component.getHeight(),
            BufferedImage.TYPE_INT_RGB
    );
// call the Component's paint method, using
    // the Graphics object of the image.
    component.paint(image.getGraphics());
    return image;
}

private static Image createImage() {
    BufferedImage img = null;
    try { 
        img = ImageIO.read(new File("oneImg.png"));
    } catch (IOException e) {
    }
    return img;
}

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Pngs());
    frame.setUndecorated(true);
    frame.getContentPane().setBackground(new Color(1.0f, 1.0f, 1.0f, 0.5f));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(512, 512);
    frame.setVisible(true);
    try { //saves the image
        // retrieve image
        BufferedImage bi = getScreenShot(frame.getContentPane());
        File outputfile = new File("saved.png");
        ImageIO.write(bi, "png", outputfile);
    } catch (IOException e) {
    }
}

}

我试图将Color构造函数的第4个参数设置为0,因此它将完全透明但我只是得到一个黑色背景。此外,当它设置为0.5f时,它根本不透明。

可能是什么问题?

2 个答案:

答案 0 :(得分:2)

使用BufferedImage.TYPE_INT_ARGB代替BufferedImage.TYPE_INT_RGB 顺便说一句:使用此代码创建正确的屏幕截图:

public static BufferedImage getScreenShot(Component component) throws AWTException {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    Robot robot = new Robot(gd);
    Rectangle bounds = new Rectangle(component.getLocationOnScreen(), component.getSize());
    return robot.createScreenCapture(bounds);
} 

答案 1 :(得分:0)

这项工作对我来说:       试试这个:

public Pngs(){  // constructor
 setBackground(new Color(0,0,0,0));
 setUndecorated(true);
 setOpacity(0.5F);

}

这使您的Jframe透明和关闭选项不可见。因此,添加退出按钮以关闭框架。 有关不透明度的详细信息,请将JFrame设为透明,请参阅THIS

相关问题