工作中,有时候会遇到需要截图的时候,如下示例两种为一个简单的实现java屏幕截图的方法,使用robot和ImgIO来实现,代码如下:
private static String defaultImageFormat="png";
public static Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
public static void snapShot(String filePath, String fileName) {
try {
File file = new File(filePath);
if(!file.exists()){
boolean create = file.mkdirs();
}
//拷贝屏幕到一个BufferedImage对象screenshot
BufferedImage screenshot = (new Robot()).createScreenCapture(new
Rectangle(0, 0, (int) d.getWidth(), (int) d.getHeight()));
//根据文件前缀变量和文件格式变量,自动生成文件名
String name=fileName+"_"+gethms()+"."+defaultImageFormat;
String imagePath = filePath+File.separator+name;
File f = new File(imagePath);
log.info("Save File "+imagePath);
//将screenshot对象写入图像文件
boolean tof = ImageIO.write(screenshot, defaultImageFormat, f);
if(tof){
log.info("图片生成成功:"+name);
}else{
log.info("图片生成失败");
}
}
catch (Exception e) {
log.error("截图失败", e);
}
}
private static String gethms(){
int hour=0;
int minute=0;
int second=0;
Calendar c=Calendar.getInstance();//获系统前期
hour=c.get(Calendar.HOUR);
minute=c.get(Calendar.MINUTE);
second=c.get(Calendar.SECOND);
String time=String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second);
return time;
}