Java Paint component into bitmap

北城以北 提交于 2019-12-23 10:09:58

问题


I need to draw the content of a component and all its subcomponents in a bitmap. The following code works perfectly if i want to draw the entire component :

public void printComponent(Component c, String format, String filename) 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);

    // Render the component and all its sub components
    c.paintAll(image.getGraphics());

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

}

but i didn't find a way for drawing only a region of this component. Any idea ?


回答1:


You need to translate like this:

BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);

Graphics g = image.getGraphics();
g.translate(-100, -100);

c.paintComponent(g);

g.dispose();

Full example with output:

public static void main(String args[]) throws Exception {

    JFrame frame = new JFrame("Test");
    frame.add(new JTable(new DefaultTableModel() {
        @Override
        public int getColumnCount() {
            return 10;
        }
        @Override
        public int getRowCount() {
            return 10;
        }
        @Override
        public Object getValueAt(int row, int column) {
            return row + " " + column;
        }
    }));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);

    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
    Graphics g = image.getGraphics();
    g.translate(-100, -100);

    frame.paintComponents(g);

    g.dispose();

    ImageIO.write(image, "png", new File("frame.png"));
}



回答2:


The Screen Image class simplifies this process for you.



来源:https://stackoverflow.com/questions/4245179/java-paint-component-into-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!