gpt4 book ai didi

java - 将 JFrame 保存为透明背景的图像

转载 作者:行者123 更新时间:2023-11-30 03:24:22 25 4
gpt4 key购买 nike

很抱歉,我知道有很多类似的问题,但我就是找不到解决方案。我尝试了不同的方法,但就是无法使背景透明。这是我的测试代码:

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 构造函数的第四个参数设置为 0,这样它将完全透明,但随后我只得到黑色背景。另外,当它设置为 0.5f 时,它根本不透明。

可能是什么问题?

最佳答案

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

关于java - 将 JFrame 保存为透明背景的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com