Java 将JComponent中的图形保存到Tiff文件中

Java 将JComponent中的图形保存到Tiff文件中,java,drawing,tiff,jcomponent,Java,Drawing,Tiff,Jcomponent,如何将JComponent中的图形保存为tiff格式?我只知道如何保存整个Java文件,但不知道如何保存特定的Jcomponent。帮助我:-( 编辑: 谢谢大家,现在我可以把我的画保存成Jpeg了 然而,我只想保存一个组件?c.paintAll(bufferedImage.getGraphics());似乎保存了整个组件。然而,我只想保存这个组件c.add(new PaintSurface(),BorderLayout.CENTER);不带面板。添加(saveBtn);我怎么做?谢谢 Cont

如何将JComponent中的图形保存为tiff格式?我只知道如何保存整个Java文件,但不知道如何保存特定的Jcomponent。帮助我:-(

编辑: 谢谢大家,现在我可以把我的画保存成Jpeg了

然而,我只想保存一个组件?
c.paintAll(bufferedImage.getGraphics());
似乎保存了整个组件。然而,我只想保存这个组件
c.add(new PaintSurface(),BorderLayout.CENTER);
不带
面板。添加(saveBtn);
我怎么做?谢谢

Container c = getContentPane();
c.setLayout(new BorderLayout());      
Panel panel = new Panel();
panel.add(saveBtn);
c.add("South", panel);
c.setBackground(Color.WHITE);
c.add(new PaintSurface(), BorderLayout.CENTER);

您可以通过创建面板大小的缓冲图像来获取组件或包含图形的面板的缓冲图像。然后,您可以将面板内容绘制到缓冲图像上。然后,您可以使用JAI(Java Advanced Imaging)库将缓冲图像保存为tiff。您必须检查其中的文档


语法可能有点偏离,我不太清楚,但这是一般的想法。然后,您可以使用JAI并将缓冲图像转换为TIFF。

这与仅使用正确语法并实际调用适当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以外的格式保存,可以使用获取JRE当前加载的所有图像输出格式的列表

更新:如果您对绘制子组件不感兴趣,可以用Component.paintAll(…)替换对Component.paintAll(…)的调用。我修改了示例代码以反映这一点。使用render the Subcomponents将subcomp设置为true并将其设置为false将忽略它们。

该类允许您保存任何组件的图像

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