如何在swing中将面板保存为图像?

时间:2023-02-09 15:47:24

Hi i want to convert panel which contains components like label and buttons to image file.

你好,我想把包含标签和按钮等组件的面板转换成图像文件。

I have done the following code. The image was saved. but the content of the panel not visible or saved. Can anyone tell me how to save the panel with its components.

我已经完成了以下代码。这张照片保存。但面板的内容不可见或保存。谁能告诉我如何用它的组件来保存面板。

Code:

代码:

package PanelToImage;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class sample extends JPanel {

public JPanel firstpanel;
public JPanel secondpanel;
JLabel label1, label2;
JButton button1, button2;

public sample() {
    firstpanel = new JPanel();
    firstpanel.setSize(400,300); 
    firstpanel.setBackground(Color.RED);
    secondpanel = new JPanel();
    secondpanel.setBackground(Color.GREEN);
    secondpanel.setSize(400,300); 

    label1 = new JLabel("label1");
    label2 = new JLabel("label2");
    button1 = new JButton("button1");
    button2 = new JButton("button2");

    firstpanel.add(label1);
    firstpanel.add(button1);

    secondpanel.add(label2);
    secondpanel.add(button2);

    saveImage(firstpanel);

    add(firstpanel);

    // add(secondpanel);
}

public static void main(String args[]) {

    JFrame frame = new JFrame();
    sample sam = new sample();
    frame.setContentPane(sam);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);

}

private void saveImage(JPanel panel) {
    BufferedImage img = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
    panel.paint(img.getGraphics());
    try {
        ImageIO.write(img, "png", new File("E://Screen.png"));
        System.out.println("panel saved as image");

    } catch (Exception e) {
        System.out.println("panel not saved" + e.getMessage());
    }
}
}

2 个解决方案

#1


17  

Tthis code works for me (in the JFrame):

Tthis code for me(在JFrame中):

Container c = getContentPane();
BufferedImage im = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
c.paint(im.getGraphics());
ImageIO.write(im, "PNG", new File("shot.png"));

Maybe you have used custom panels. If true, try to add super.paint(g) at the beginning of the paint methods of your panels.

也许你用过自定义面板。如果是的话,试着在你的面板的绘制方法的开头添加super.paint(g)。

EDIT: You have to call saveImage after display the frame:

编辑:显示帧后必须调用saveImage:

public static void main(String args[]) {
    ...
    frame.setSize(400, 300);
    sam.saveImage(sam.firstpanel);
}

EDIT 2: This is the saved image (is little because the layout, but is the proof that it should work):

编辑2:这是保存的图像(因为布局小,但是是它应该工作的证明):

如何在swing中将面板保存为图像?

I called the saveImage as last call in the main, and used a file in the user dir (new File("Screen.png")) as nIcE cOw said.

我将saveImage调用为main中的最后一次调用,并使用了user dir (new file(“Screen.png”)中的一个文件。

#2


5  

Here try this example program, instead of using getGraphics() seems like you have to use createGraphics() for the BufferedImage you are about to make.

在这里尝试这个示例程序,而不是使用getGraphics(),似乎您必须为您将要创建的BufferedImage使用createGraphics()。

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SnapshotExample
{
    private JPanel contentPane;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Snapshot Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        JLabel label = new JLabel("This JLabel will display"
                        + " itself on the SNAPSHOT", JLabel.CENTER);
        contentPane.add(label);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        makePanelImage(contentPane);
    }

    private void makePanelImage(Component panel)
    {
        Dimension size = panel.getSize();
        BufferedImage image = new BufferedImage(
                    size.width, size.height 
                              , BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        panel.paint(g2);
        try
        {
            ImageIO.write(image, "png", new File("snapshot.png"));
            System.out.println("Panel saved as Image.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {           
                new SnapshotExample().displayGUI();
            }
        });
    }
}

#1


17  

Tthis code works for me (in the JFrame):

Tthis code for me(在JFrame中):

Container c = getContentPane();
BufferedImage im = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
c.paint(im.getGraphics());
ImageIO.write(im, "PNG", new File("shot.png"));

Maybe you have used custom panels. If true, try to add super.paint(g) at the beginning of the paint methods of your panels.

也许你用过自定义面板。如果是的话,试着在你的面板的绘制方法的开头添加super.paint(g)。

EDIT: You have to call saveImage after display the frame:

编辑:显示帧后必须调用saveImage:

public static void main(String args[]) {
    ...
    frame.setSize(400, 300);
    sam.saveImage(sam.firstpanel);
}

EDIT 2: This is the saved image (is little because the layout, but is the proof that it should work):

编辑2:这是保存的图像(因为布局小,但是是它应该工作的证明):

如何在swing中将面板保存为图像?

I called the saveImage as last call in the main, and used a file in the user dir (new File("Screen.png")) as nIcE cOw said.

我将saveImage调用为main中的最后一次调用,并使用了user dir (new file(“Screen.png”)中的一个文件。

#2


5  

Here try this example program, instead of using getGraphics() seems like you have to use createGraphics() for the BufferedImage you are about to make.

在这里尝试这个示例程序,而不是使用getGraphics(),似乎您必须为您将要创建的BufferedImage使用createGraphics()。

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SnapshotExample
{
    private JPanel contentPane;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Snapshot Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setOpaque(true);
        contentPane.setBackground(Color.WHITE);
        JLabel label = new JLabel("This JLabel will display"
                        + " itself on the SNAPSHOT", JLabel.CENTER);
        contentPane.add(label);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);

        makePanelImage(contentPane);
    }

    private void makePanelImage(Component panel)
    {
        Dimension size = panel.getSize();
        BufferedImage image = new BufferedImage(
                    size.width, size.height 
                              , BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        panel.paint(g2);
        try
        {
            ImageIO.write(image, "png", new File("snapshot.png"));
            System.out.println("Panel saved as Image.");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {           
                new SnapshotExample().displayGUI();
            }
        });
    }
}