0

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

已编辑:谢谢大家,现在我可以将我的绘图保存到 Jpeg。

但是我只想保存其中一个组件?c.paintAll(bufferedImage.getGraphics());似乎可以保存整个组件。但是,我只想保存这个组件, c.add(new PaintSurface(), BorderLayout.CENTER);我该panel.add(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);
4

3 回答 3

1

这与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 将忽略它们。

于 2009-10-06T22:53:56.880 回答
0

您可以通过创建面板大小的缓冲图像来获取组件或包含绘图的面板的缓冲图像。然后,您可以将面板内容绘制到缓冲图像上。然后,您可以使用 JAI(Java 高级成像)库将缓冲图像保存为 tiff。您必须在此处查看相关文档。

JComponent component;  //this is your already created component
BufferedImage image = new BufferedImage(component.getWidth(),
                                        component.getHeight(),
                                        Bufferedimage.TYPERGB)

Graphics g = image.getGraphics;
component.paintComponent(g);

语法可能略有偏差,我不知道,但这是一般的想法。然后,您可以使用 JAI 并将缓冲图像转换为 TIFF。

于 2009-10-06T22:43:47.350 回答
0

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

于 2009-10-06T23:49:37.697 回答