Contents of a JPanel as a BufferedImage

A

Aaron Fude

Hi,

If I drew a bunch of stuff to a JPanel, can I obtain the contents as a
BufferedImage?

Many thanks in advance,

Aaron
 
A

Aaron Fude

Hi,

If I drew a bunch of stuff to a JPanel, can I obtain the contents as a
BufferedImage?

Many thanks in advance,

Aaron

Just to clarify, I'm looking to capture the pixels that are already
there. So I can use the approach where I just paint to an
image.getGraphics().

Thank you.

Aaron
 
K

Knute Johnson

Aaron said:
Hi,

If I drew a bunch of stuff to a JPanel, can I obtain the contents as a
BufferedImage?

Many thanks in advance,

Aaron

If your drawing code is all in the paintComponent() method (where it
should be), you can create a BufferedImage and call paintComponent()
with the Graphics object you get from the BufferedImage. If it isn't,
create the image before you draw to your JPanel and draw to both at the
same time.

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class test extends JPanel {
public test() {
setPreferredSize(new Dimension(400,300));
}

public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(Color.GREEN);
g.drawLine(0,0,getWidth(),getHeight());
g.drawLine(getWidth(),0,0,getHeight());
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final test t = new test();
f.add(t,BorderLayout.CENTER);
JButton b = new JButton("Save Image");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
BufferedImage bi = new BufferedImage(
t.getWidth(),t.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
t.paintComponent(g);
try {
ImageIO.write(bi,"JPEG",
new File("image.jpg"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
f.add(b,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
});
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,048
Members
48,769
Latest member
Clifft

Latest Threads

Top