本文目录导读:

我来介绍几种Java实现截屏的常用方法:
使用Robot类(最常用)
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ScreenCaptureDemo {
// 全屏截取
public static void captureFullScreen(String filePath) {
try {
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenCapture = robot.createScreenCapture(screenRect);
ImageIO.write(screenCapture, "png", new File(filePath));
System.out.println("全屏截图保存成功: " + filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
// 指定区域截取
public static void captureRegion(Rectangle region, String filePath) {
try {
Robot robot = new Robot();
BufferedImage screenCapture = robot.createScreenCapture(region);
ImageIO.write(screenCapture, "png", new File(filePath));
System.out.println("区域截图保存成功: " + filePath);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 全屏截图
captureFullScreen("full_screen.png");
// 指定区域截图 (x, y, width, height)
captureRegion(new Rectangle(100, 100, 500, 400), "region.png");
}
}
带GUI界面的截屏程序
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ScreenCaptureGUI extends JFrame {
private JButton captureBtn;
public ScreenCaptureGUI() {
initUI();
}
private void initUI() {
setTitle("屏幕截图工具");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
captureBtn = new JButton("开始截图");
captureBtn.addActionListener(e -> startCapture());
setLayout(new FlowLayout());
add(captureBtn);
}
private void startCapture() {
setVisible(false);
try {
Thread.sleep(500); // 等待窗口隐藏
Robot robot = new Robot();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRect = new Rectangle(screenSize);
BufferedImage capture = robot.createScreenCapture(screenRect);
// 保存文件
String fileName = "screenshot_" + System.currentTimeMillis() + ".png";
ImageIO.write(capture, "png", new File(fileName));
JOptionPane.showMessageDialog(this, "截图已保存为: " + fileName);
} catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ScreenCaptureGUI().setVisible(true);
});
}
}
带选择框的区域截图
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class SelectableCapture extends JWindow {
private Point startPoint;
private Point endPoint;
private static BufferedImage screenshot;
public SelectableCapture() {
initComponents();
}
private void initComponents() {
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
}
@Override
public void mouseReleased(MouseEvent e) {
endPoint = e.getPoint();
captureSelectedArea();
dispose();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
endPoint = e.getPoint();
repaint();
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (screenshot != null) {
g.drawImage(screenshot, 0, 0, this);
}
if (startPoint != null && endPoint != null) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(0, 100, 255, 100));
g2d.setStroke(new BasicStroke(2));
int x = Math.min(startPoint.x, endPoint.x);
int y = Math.min(startPoint.y, endPoint.y);
int width = Math.abs(endPoint.x - startPoint.x);
int height = Math.abs(endPoint.y - startPoint.y);
g2d.fillRect(x, y, width, height);
g2d.setColor(Color.BLUE);
g2d.drawRect(x, y, width, height);
}
}
private void captureSelectedArea() {
try {
int x = Math.min(startPoint.x, endPoint.x);
int y = Math.min(startPoint.y, endPoint.y);
int width = Math.abs(endPoint.x - startPoint.x);
int height = Math.abs(endPoint.y - startPoint.y);
Robot robot = new Robot();
BufferedImage selectedArea = robot.createScreenCapture(new Rectangle(x, y, width, height));
String fileName = "region_capture_" + System.currentTimeMillis() + ".png";
ImageIO.write(selectedArea, "png", new File(fileName));
System.out.println("区域截图已保存: " + fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
screenshot = robot.createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
SelectableCapture capture = new SelectableCapture();
capture.setVisible(true);
}
}
定时截图功能
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
public class TimedCapture {
private static int counter = 0;
public static void startTimedCapture(int intervalSeconds, int totalShots) {
TimerTask task = new TimerTask() {
@Override
public void run() {
try {
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = robot.createScreenCapture(screenRect);
String fileName = "timed_" + counter + "_" +
System.currentTimeMillis() + ".png";
ImageIO.write(capture, "png", new File(fileName));
System.out.println("第 " + (counter + 1) + " 次截图: " + fileName);
counter++;
if (counter >= totalShots) {
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer();
timer.schedule(task, 0, intervalSeconds * 1000);
}
public static void main(String[] args) {
// 每5秒截图一次,共截图10次
startTimedCapture(5, 10);
}
}
多显示器支持
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class MultiMonitorCapture {
public static void captureAllMonitors(String outputDir) {
try {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
for (int i = 0; i < screens.length; i++) {
GraphicsConfiguration[] configs = screens[i].getConfigurations();
for (GraphicsConfiguration config : configs) {
Rectangle bounds = config.getBounds();
Robot robot = new Robot(screens[i]);
BufferedImage capture = robot.createScreenCapture(bounds);
String fileName = outputDir + "/monitor_" + i + "_" +
System.currentTimeMillis() + ".png";
ImageIO.write(capture, "png", new File(fileName));
System.out.println("显示器 " + i + " 截图保存: " + fileName);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
captureAllMonitors(".");
}
}
注意事项
- 权限问题:在某些操作系统上可能需要相应权限
- 格式支持:常用格式有 PNG、JPG、BMP
- 性能考虑:全屏截图可能占用较多内存
- 多线程:截图操作应在单独线程中执行,避免阻塞UI
这些代码可以根据你的具体需求进行修改和扩展。