Java - 获取JPanel的图像

时间:2012-06-19 17:09:24

标签: java swing jpanel bufferedimage

我正在写一个程序,我在JPanel上绘画。如何获得在其上绘制的Image JPanel? 我尝试了这段代码,但我得到的是一张空白图像,背景颜色为JPanelBufferedImage不包含我的面板上绘制的内容。

    private BufferedImage createImage(JPanel panel) {    
        int w = panel.getWidth();
        int h = panel.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        panel.paint(g);
        return bi;
    }

我做错了什么?

3 个答案:

答案 0 :(得分:2)

这是一个SSCCE,说明它有效。一个常见错误是将null作为ImageObserver方法的drawImage传递,因为图像的加载是异步的。

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestPrint {

    protected static void initUI() throws MalformedURLException {
        final ImageIcon image = new ImageIcon(new URL("http://www.travelblog.org/Wallpaper/pix/tb_fiji_sunset_wallpaper.jpg"));
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(java.awt.Graphics g) {
                super.paintComponent(g);
                g.drawImage(image.getImage(), 0, 0, this);
            };
        };
        panel.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
        panel.setSize(panel.getPreferredSize());
        BufferedImage bi = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics g = bi.createGraphics();
        panel.print(g);
        g.dispose();
        try {
            ImageIO.write(bi, "png", new File("test.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}

答案 1 :(得分:2)

您的代码适合我。

这是一个简单的例子。调整框架大小以查看面板更改大小并移动图像。

public static void main(String[] args) {
    JFrame frame = new JFrame("Test");
    JPanel panel = new JPanel();
    panel.setBackground(Color.BLUE);
    JLabel label = new JLabel("Image");
    label.setForeground(Color.RED);
    panel.add(label);
    frame.add(panel, BorderLayout.NORTH);
    frame.pack();
    JLabel image = new JLabel(new ImageIcon(createImage(panel)));
    frame.add(image, BorderLayout.SOUTH);
    frame.pack();
    label.setText("Original");      
    frame.setVisible(true);
}

private static BufferedImage createImage(JPanel panel) {
    int w = panel.getWidth();
    int h = panel.getHeight();
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    panel.paint(g);
    return bi;
}

所以你的问题必须在其他地方。确保您的面板在创建图像时具有正尺寸。

答案 2 :(得分:2)

这是一个快速示例方法,您可以将其添加到任何Java 2 / JDK 1.2应用程序中。只需传入要快照的组件和要保存的文件名即可。

public void saveComponentAsJPEG(Component myComponent, String filename) {
    Dimension size = myComponent.getSize();
    BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = myImage.createGraphics();
    myComponent.paint(g2);
    try {
        OutputStream out = new FileOutputStream(filename);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(myImage);
        out.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

这种方法非常通用。它可用于拍摄各种Java应用程序组件的快照。但请注意,使用com.sun.image.codec.jpeg会对代码的可移植性造成一定的风险。

编辑: 我测试了代码以确保并且一切似乎都很好:

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScreenCapture extends JFrame {

    public ScreenCapture() {
        createAndShowUI();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ScreenCapture screenCapture = new ScreenCapture();
            }
        });
    }

    private void createAndShowUI() {
        setTitle("Test Screen Capture");
        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        getContentPane().add(new DrawingPanel());
        setVisible(true);
        saveComponentAsJPEG(this, "C:/test.jpg");

    }

    public void saveComponentAsJPEG(Component myComponent, String filename) {
        Dimension size = myComponent.getSize();
        BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = myImage.createGraphics();
        myComponent.paint(g2);
        try {
            OutputStream out = new FileOutputStream(filename);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(myImage);
            out.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    class DrawingPanel extends JPanel {

        public DrawingPanel() {
            setDoubleBuffered(true);
        }

        @Override
        public void paintComponent(Graphics grphcs) {
            super.paintComponents(grphcs);
            Graphics2D g2d = (Graphics2D) grphcs;

            RenderingHints rhints = g2d.getRenderingHints();
            boolean antialiasOn = rhints.containsValue(RenderingHints.VALUE_ANTIALIAS_ON);

            if (!antialiasOn) {
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            }

            Shape circle = new Ellipse2D.Float(100.0f, 100.0f, 100.0f, 100.0f);

            g2d.setColor(Color.RED);
            g2d.draw(circle);
            g2d.fill(circle);
        }
    }
}