gpt4 book ai didi

java - 将 JPanel 图形导出为 .png 或 .gif 或 .jpg

转载 作者:搜寻专家 更新时间:2023-10-30 19:46:40 29 4
gpt4 key购买 nike

我正在尝试使用 Java 开发某种绘画。

我有一个位于 JPanel 内部的 JComponent。

我已经可以在该 JComponent 中绘制线条和矩形。

现在,我如何将这些绘图导出为图像(png、gif、jpg)?

我试过这个:

BufferedImage b = new BufferedImage(1700,1100,BufferedImage.TYPE_INT_RGB);
this.print(getGraphics());
try{ImageIO.write(b,"png",new File("test.png"));}catch (Exception e) {}

但这只会创建一个全黑的 .png 文件。

求助!!!

已解决!!!

BufferedImage bi = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_ARGB); 
Graphics g = bi.createGraphics();
this.paint(g); //this == JComponent
g.dispose();
try{ImageIO.write(bi,"png",new File("test.png"));}catch (Exception e) {}

最佳答案

首先,print() 是错误的方法。我想应该起作用的(还没有测试过)是:获取 BufferedImage 的图形 (b.createGraphics()) 并将该图形对象用于 paint() 您的面板/组件。

(例如 yourPanel.paint(b.createGraphics());)

关于java - 将 JPanel 图形导出为 .png 或 .gif 或 .jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5655908/

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