将JPanel Graphics导出为.png或.gif或.jpg [英] Export JPanel Graphics to .png or .gif or .jpg
问题描述
我有一个位于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文件。
帮助!!!
RESOLVED !!!
BufferedImage bi = new BufferedImage this.getSize()。width,this.getSize()。height,BufferedImage.TYPE_INT_ARGB);
图形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());
)
I'm trying to develop some sort of paint using Java.
I have a JComponent that is located inside of a JPanel.
I already can draw lines and rectangles into that JComponent.
Now, how can I export this drawings as an image (png, gif, jpg)?
I tried this:
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) {}
But that only creates a .png file all black.
Help!!!
RESOLVED!!!
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) {}
First of all, print()
is the incorrect method.
What I guess should work (haven't tested it yet) is:
get the BufferedImage
's Graphics (b.createGraphics()
) and use that graphics object to paint()
your panel/component.
(e.g. yourPanel.paint(b.createGraphics());
)
这篇关于将JPanel Graphics导出为.png或.gif或.jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!