java - 将 JComponent 中的绘图保存到 Tiff 文件中

标签 java drawing tiff jcomponent

如何将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);

最佳答案

这与 broschb's 基本相同仅使用正确的语法并实际调用适当的 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(...) 的调用。我更改了示例代码以反射(reflect)这一点。将 subcomp 设置为 true 并渲染子组件并将其设置为 false 将忽略它们。

关于java - 将 JComponent 中的绘图保存到 Tiff 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1528458/

相关文章:

objective-c - 我的程序大部分时间都花在 objc_msgSend 上。这是否意味着 Objective-C 的性能很差?

c++ - 使用 C++ 读取 tiff 图像

java - 如何使用java从GeoTIFF图像中提取纬度和经度值?

c# - 我如何使用 LibTiff.Net 2.3 库编写像 200/1 这样的理性标签

javascript - 无法在android中登录webview

java - 文件提供程序不工作

google-maps - 如何在android中的 map 触摸位置动态绘制形状

java - 尝试使用 javacv 使用 ffmpeg 加载视频文件

java - 如果我在 Java 中覆盖 'equals' 方法,为什么需要覆盖 hashcode?

algorithm - 绘制直径均匀的同心圆