效果图如下:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.CubicCurve2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
public class ComponentToImage extends Canvas {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
g2.setPaint(getBackground());
g2.fillRect(0,0,w,h);
g2.setPaint(Color.red);
g2.draw(new CubicCurve2D.Double(w/4, h*3/4, -w*3/8, -h/4,
w*11/8, -h/4, w*3/4, h*3/4));
}
private BufferedImage makeImage() {
int w = getWidth();
int h = getHeight();
int type = BufferedImage.TYPE_INT_RGB;
BufferedImage image = new BufferedImage(w,h,type);
Graphics2D g2 = image.createGraphics();
paint(g2);
g2.dispose();
return image;
}
private void save(BufferedImage image) {
String ext = "jpg"; // png, bmp (j2se 1.5+), gif (j2se 1.6+)
File file = new File("componentToImage." + ext);
try {
ImageIO.write(image, ext, file);
} catch(IOException e) {
System.out.println("write error: " + e.getMessage());
}
}
private void saveToFile() {
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
save(makeImage());
}
}).start();
}
public static void main(String[] args) {
ComponentToImage test = new ComponentToImage();
Frame f = new Frame();
f.addWindowListener(closer);
f.add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
test.saveToFile();
}
private static WindowListener closer = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
}