这是一个可以添加到任何 Java 2/JDK 1.2 应用程序的快速示例方法。只需传入要快照的组件和要保存到的文件名。
public void saveComponentAsJPEG(Component myComponent, String filename) {
Dimension size = myComponent.getSize();
BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myImage.createGraphics();
myComponent.paint(g2);
try {
OutputStream out = new FileOutputStream(filename);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(myImage);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
这种方法非常通用。它可用于拍摄各种 Java 应用程序组件的快照。但是,请注意,您使用 com.sun.image.codec.jpeg 可能会影响代码的可移植性。
编辑:我测试了代码以确保一切正常:
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ScreenCapture extends JFrame {
public ScreenCapture() {
createAndShowUI();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
ScreenCapture screenCapture = new ScreenCapture();
}
});
}
private void createAndShowUI() {
setTitle("Test Screen Capture");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
getContentPane().add(new DrawingPanel());
setVisible(true);
saveComponentAsJPEG(this, "C:/test.jpg");
}
public void saveComponentAsJPEG(Component myComponent, String filename) {
Dimension size = myComponent.getSize();
BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myImage.createGraphics();
myComponent.paint(g2);
try {
OutputStream out = new FileOutputStream(filename);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(myImage);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
class DrawingPanel extends JPanel {
public DrawingPanel() {
setDoubleBuffered(true);
}
@Override
public void paintComponent(Graphics grphcs) {
super.paintComponents(grphcs);
Graphics2D g2d = (Graphics2D) grphcs;
RenderingHints rhints = g2d.getRenderingHints();
boolean antialiasOn = rhints.containsValue(RenderingHints.VALUE_ANTIALIAS_ON);
if (!antialiasOn) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
Shape circle = new Ellipse2D.Float(100.0f, 100.0f, 100.0f, 100.0f);
g2d.setColor(Color.RED);
g2d.draw(circle);
g2d.fill(circle);
}
}
}