Here is the code I used to dump a "colorscan" display of some sensor data to an image file so I could fiddle with it in an external image processing package. Our component was using an offscreen Image buffer to draw on and then rendering with g.drawImage() in the paintComponent method, so I already had an Image of the panel, but I fiddled with the code just a bit and the following should work for you if you don't need to save the frame decorations (title bar, etc), just the contents .
The action listener code to save:
public void actionPerformed(java.awt.event.ActionEvent e){
try {
File saveFile = new File(jobFile+"_colorscan@"+centerSampleIndex+".gif");
Image img = createImage(getWidth(),getHeight());
Graphics g = img.getGraphics();
paint(g);
ImageIO.write(toBufferedImage(img),"gif",saveFile);
JOptionPane.showMessageDialog(null,"Image saved to "+saveFile.toString());
g.dispose();
} catch (Exception ex){
ex.printStackTrace();
}
}
The method to convert the Image to a BufferedImage (which I found in some example somewhere):
// This method returns a buffered image with the contents of an image
private BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see e661 Determining If an Image Has Transparent Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the …