这与broschb 的解决方案基本相同,只是使用正确的语法并实际调用适当的 JAI 例程。
public void saveComponentAsTiff(Component c, String filename, boolean subcomp) throws IOException {
saveComponentTiff(c, "tiff", filename, subcomp);
}
public void saveComponent(Component c, String format, String filename, boolean subcomp) throws IOException {
// Create a renderable image with the same width and height as the component
BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
if(subcomp) {
// Render the component and all its sub components
c.paintAll(image.getGraphics());
}
else {
// Render the component and ignoring its sub components
c.paint(image.getGraphics());
}
// Save the image out to file
ImageIO.write(image, format, new File(filename));
}
可以在此处找到各种功能的文档:
如果要以 tiff 以外的格式保存,可以使用ImageIO.getWriterFormatNames()获取 JRE 当前加载的所有图像输出格式的列表。
更新:如果您对绘制子组件不感兴趣,您可以用 Component.paint(...) 替换对 Component.paintAll(...) 的调用。我已经更改了示例代码以反映这一点。将 subcomp 设置为 true 并渲染子组件并将其设置为 false 将忽略它们。