5

我正在编写一个程序,我在JPanel. 我怎样才能得到一个画在上面ImageJPanel东西?我尝试了这段代码,但我得到的只是一张空白图像,其背景颜色为JPanel. BufferedImage不包含在我的面板上绘制的内容。

    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;
    }

我究竟做错了什么?

4

3 回答 3

2

这是一个 SSCCE 说明它的工作原理。一个常见的错误是传递nullas ImageObserverofdrawImage方法,因为图像的加载是异步的。

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();
                }
            }
        });
    }
}
于 2012-06-19T17:16:08.007 回答
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;
}

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

于 2012-06-19T17:17:25.420 回答
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);
        }
    }
}
于 2012-06-19T17:22:12.783 回答