How to get the image of a panel?

I

InterKOT

Hi guys.

Assuming I have a panel extended from the Swing JPanel on which I draw some
shapes like lines, rectangles etc. Is there any way to obtain the image of this
panel at runtime so that i can be saved as a gif or bmp file?

Thanks,

Sebastian
 
I

Ike

import com.sun.image.codec.jpeg.*;

final static public void savePanelAsJPG(JPanel r, java.io_OutputStream out)
{
try {
/* get the image on the Panel */
BufferedImage buffy = new
BufferedImage(r.getWidth(),r.getHeight(),
java.awt.image.BufferedImage.TYPE_INT_RGB);
Graphics g = buffy.getGraphics();
r.paint(g);
g.dispose();
/* encodes expImage as a JPEG data stream */
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param =
encoder.getDefaultJPEGEncodeParam(buffy);
param.setQuality(1.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(buffy);
} catch (Exception ex) {
System.out.println(ex);
}
}

//Ike
 
T

Tor Iver Wilhelmsen

Assuming I have a panel extended from the Swing JPanel on which I
draw some shapes like lines, rectangles etc. Is there any way to
obtain the image of this panel at runtime so that i can be saved as
a gif or bmp file?

Two ways, in fact:

1) If you do all the draing in paintComponent(), just call that method
passing the Graphics of a BufferedImage, the use the Java image
APIs to save as a file.

2) Use java.awt.Robot.createScreenCapture() where the Panel is to get
a BufferedImage then use the image API as mentioned above.
 

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

No members online now.

Forum statistics

Threads
474,444
Messages
2,571,709
Members
48,796
Latest member
Greg L.
Top