You need JDK 1.4, which has the optional package ImageIO. The version of ImageIO for JDK 1.3.1 you can find in early access does not seem to save images properly, at least with the following examples.
If you want to edit your graphics with AWT, you cannot use the technique I used in the second example. The first example works both with AWT and Swing.
Example 1 (AWT and Swing):
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class SaveAWT
{
public static void main(String[] args)
{
Frame frame = new Frame("Hello there!");
frame.setBounds(100, 100, 300, 200);
frame.show();
try
{
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(frame.getBounds());
ImageIO.write(image, "png", new File("frame.png"));
}
catch(Throwable thr) { thr.printStackTrace(); }
System.exit(0);
}
}
Example 2 (Swing only)
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class SaveSwing
{
public static void main(String[] args)
{
JFrame jframe = new JFrame("Hello there!");
jframe.setBounds(100, 100, 300, 200);
Container cp = jframe.getContentPane();
cp.add(new JLabel("Can you save me?"));
jframe.show();
BufferedImage image = new BufferedImage(cp.getWidth(), cp.getHeight(),
BufferedImage.TYPE_3BYTE_BGR);
cp.paint(image.getGraphics());
try { ImageIO.write(image, "png", new File("jframe.png")); }
catch(Throwable thr) { thr.printStackTrace(); }
System.exit(0);
}
}
There is a way to save in JPEG format any graphical object you want using the class JPEGImageEncoder by its "image".
This class is part of the package com.sun.image.codec which is included in the rt.jar of the JDK.
The steps you have to follow are:
1) Create a BufferedImage
2) Get the graphic context for this image and render your image on it
3) Create a JPEGImageEncoder and encode your image
4) Flush the content of the encoder on a OutputStream (i.e. a file)
This steps are reported also on JDK Tech Tips of 21st August.
TopFoxy