Search code examples
javaimageswingtransparency

Save JFrame as image with transparent background


I'm sorry I know there are a lot of questions like that but I just couldn't find the solution. I tried different things but just I can't get the background transparent. Here is my test code:

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) {
    }
}

}

I tried to set the 4th argument of the Color constructor to 0 so it will be fully transparent but then I just get a black background. Also when it is set to 0.5f it's not transparent at all.

What could be the problem?


Solution

  • Use BufferedImage.TYPE_INT_ARGB instead of BufferedImage.TYPE_INT_RGB.
    By the way: Use this code to create proper screenshots:

    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);
    }