话不多说直接上代码
/**
* 屏幕截图
*
* @param imageName 存储图片名称 比如: screen
* @param path 图片路径 比如: C:\Users\NineSun\Desktop\java实现屏幕截图\
* @param imgType 图片类型 png 或 jpg
* @throws AWTException
* @throws IOException
*/
public static String cutPic(String imageName, String path, String imgType) throws AWTException, IOException {
System.out.println("开始截图");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
//首先创建一个目录
File file = new File(path);
if (!file.isDirectory() || !file.exists()) {
file.mkdir();
}
//判断文件是否存在,存在就改名字
String fileName = imageName + "." + imgType;
ImageIO.write(image, imgType, new File(path + fileName));
String filePath = path + fileName;
return filePath;
}
如何使用:
public static void main(String[] args) throws IOException, AWTException {
cutPic("test", "C:\\Users\\NineSun\\Desktop\\cd\\", "png");
}
如果我们运行时出现java.awt.HeadlessException: null这种错误,解决方式如下:
- 1.在idea中运行:
输入:
-Djava.awt.headless=false
- 2.如果我们需要打包运行,则需要我们修改主配置类,修改成以下内容:
@SpringBootApplication
public class ScreenShareApplication {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(ScreenShareApplication.class);
builder.headless(false).run(args);
}
}
至此,实现屏幕截图的功能就结束了