public RobotService() {
try {
robot = new Robot();//核心机器人类,用于截图,键盘或鼠标事件的重放执行。
DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDisplayMode();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)screensize.getWidth();
int height = (int)screensize.getHeight();
realhight = height;
realwidth = width;
System.out.println("宽度:" + width + " 高度:" + height);
rectangle = new Rectangle(0, 0, displayMode.getWidth(), displayMode.getHeight());
} catch (AWTException e) {
logger.error("",e);
}
}
通过getCapture方法获取截图
private byte[] getCapture(Robot robot,Rectangle rectangle) {
BufferedImage bufferedImage = robot.createScreenCapture(rectangle);
//获得一个内存输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//将图片数据写入内存流中
try {
Thumbnails.of(bufferedImage).scale(1.0f).outputQuality(0.5f).outputFormat("jpg").toOutputStream(baos);
} catch (Exception e) {
logger.error("图片写入出现异常",e);
}
return baos.toByteArray();
}