网上很多Java截屏的资料信息,但是涉及到多显示器截屏的却很少。
下面直接上代码说一下思路
先看一下网上大部分的截屏方式
public class Main {
public static void main(String[] args) throws Exception {
// 获取当前屏幕大小
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// 指定捕获屏幕区域大小,这里使用全屏捕获
Rectangle rectangle = new Rectangle(screenSize);
// 截屏操作
BufferedImage bufImage = new Robot().createScreenCapture(rectangle );
// 保存截取的图片
ImageIO.write(bufImage, "PNG", new File("capture.png"));
}
}
然后我就想获取系统的,得到两个显示器的信息
//省略...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gds = ge.getScreenDevices();
for (int i = 0; i < gs.length; i++) {
Robot robot = new Robot(gs[i]);
BufferedImage img = robot.createScreenCapture(rectangle);
//省略...
}
按理说上面这种方式是可以的,拿两个显示器的对象获取到Robot进行截屏,但是结果并不行。
所以我就想那就手动设置一个满足两块屏幕大小的矩形,就有了下面的方案
/**
* 屏幕快照
*/
public static void screenSnapshot() {
//本地环境
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//获取本地屏幕设备列表
GraphicsDevice[] gds = ge.getScreenDevices();
log.info("找到" + gds.length + "个屏幕设备");
int width = 0;
int height = 0;
int x = 0;
int y = 0;
for (GraphicsDevice gd : gds) {
//获取屏幕宽度
width += gd.getDisplayMode().getWidth();
//获取屏幕高度,取最大值保证最高屏幕
if (gd.getDisplayMode().getHeight() > height) {
height = gd.getDisplayMode().getHeight();
}
GraphicsConfiguration gc = gd.getDefaultConfiguration();
//获取x轴顶点, x轴取最小顶点保证最宽屏幕
if (gc.getBounds().x < x) {
x = gc.getBounds().x;
}
//获取y轴顶点, y轴取最大顶点保证最高屏幕
if (gc.getBounds().y > y) {
y = gc.getBounds().y;
}
}
log.info("当前截取的屏幕参数,x:{},y:{},宽度:{},高度:{}", x, y, width, height);
// 指定捕获屏幕区域大小
Rectangle rectangle = new Rectangle(x, y, width, height);
try {
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);
if (img != null) {
// 从当前屏幕中读取的像素图像,该图像不包括鼠标光标
BufferedImage image = robot.createScreenCapture(rectangle);
ImageIO.write(image, "JPEG", new File("D://img//456.JPEG"));
log.info("屏幕快照完成");
}
} catch (AWTException | IOException e) {
log.error("屏幕快照获取异常!{}", e);
}
}
看到这里如果对你有帮助,请点个赞支持一下哦。