gpt4 book ai didi

Java - 获取 JPanel 的图像

转载 作者:搜寻专家 更新时间:2023-10-31 19:57:11 25 4
gpt4 key购买 nike

我正在编写一个程序,其中我在 JPanel 上作画。如何获取绘制在其上的 JPanelImage?我尝试了这段代码,但我得到的只是一张空白图像,其背景色为我的 JPanelBufferedImage 不包含在我的面板上绘制的内容。

    private BufferedImage createImage(JPanel panel) {    
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
return bi;
}

我做错了什么?

最佳答案

这是一个 SSCCE,说明它的工作原理。一个常见的错误是将 null 作为 drawImage 方法的 ImageObserver 传递,因为图像的加载是异步的。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestPrint {

protected static void initUI() throws MalformedURLException {
final ImageIcon image = new ImageIcon(new URL("http://www.travelblog.org/Wallpaper/pix/tb_fiji_sunset_wallpaper.jpg"));
JPanel panel = new JPanel() {
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
g.drawImage(image.getImage(), 0, 0, this);
};
};
panel.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
panel.setSize(panel.getPreferredSize());
BufferedImage bi = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
panel.print(g);
g.dispose();
try {
ImageIO.write(bi, "png", new File("test.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
try {
initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}

关于Java - 获取 JPanel 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11105915/

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