가장 먼저 떠오르는 것은 AWT를 사용하여 화면 캡처를 캡처하는 것입니다 (아래 코드 참조). JEditorPane, JDICWebBrowser 컨트롤 또는 SWTBrowser (AWT embedding support 통해)을 캡처 할 수 있습니다. 후자의 두 개는 네이티브 브라우저 (IE, Firefox)를 포함하므로 의존성을 도입합니다. JEditorPane HTML 지원은 HTML 3.2에서 중단되었습니다. 이들 중 어느 것도 헤드리스 시스템에서 작동하지 않을 수도 있습니다.
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
public class Capture {
private static final int WIDTH = 128;
private static final int HEIGHT = 128;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
public void capture(Component component) {
component.setSize(image.getWidth(), image.getHeight());
Graphics2D g = image.createGraphics();
try {
component.paint(g);
} finally {
g.dispose();
}
}
private BufferedImage getScaledImage(int width, int height) {
BufferedImage buffer = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffer.createGraphics();
try {
g.drawImage(image, 0, 0, width, height, null);
} finally {
g.dispose();
}
return buffer;
}
public void save(File png, int width, int height) throws IOException {
ImageIO.write(getScaledImage(width, height), "png", png);
}
public static void main(String[] args) throws IOException {
JLabel label = new JLabel();
label.setText("Hello, World!");
label.setOpaque(true);
Capture cap = new Capture();
cap.capture(label);
cap.save(new File("foo.png"), 64, 64);
}
}