Spring boot 截图java.awt.HeadlessException: null处理
截图源代码:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* ImageIO【保存成文件】、BufferedImage【临时存储】、Robot【截取】
* */
public class Images {
//文件全称(imageName.imageType)
private String name;
//文件名
private String imageName;
//文件类型
private String imageType;
//屏幕
private Dimension dimension;
//图片存放路径
private String path;
//截取矩形
private Rectangle rectangle;
//初始化属性
public Images(){
//设置图片存放路径
path="D:/aaaa/";
//获取屏幕矩形属性
dimension=Toolkit.getDefaultToolkit().getScreenSize();
//将屏幕矩形属性赋予截取矩形
rectangle=new Rectangle(0,0,1366,736);
System.out.println(rectangle);
//设置文件类型
imageType="png";
}
//截屏
public void getImages(){
//设置文件名
imageName=UUID.randomUUID().toString();
//设置文件全称
name=imageName+"."+imageType;
//获取file类
File imagePath=new File(path);
//判断文件目录是否存在,若不存在则创建
if(!imagePath.exists()){
imagePath.mkdir();
}
//开始截屏
//使用了 java.awt包 BufferedImage
BufferedImage bufferedImage=null;
//使用了 java.awt包 Robot
//会抛异常,使用try catch 捞异常
try {
Robot robot=new Robot();
//获取指定的图片
bufferedImage = robot.createScreenCapture(rectangle);
} catch (AWTException e) {
e.printStackTrace();
}
//使用 javax.imageio包 ImageIO
try {
//参数为 获取的图片,图片的类型,文件流(存储路径,文件名)
File file=new File(path,name);
ImageIO.write(bufferedImage,imageType,file);
//自动打开
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
Desktop.getDesktop().open(file);
}
System.out.println(name);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("开始执行");
Images images=new Images();
images.getImages();
System.out.println("执行完毕");
}
}
但是Images类在Spring boot 调用时会报错 -.-
错误如下:
用了好久时间总算查出了bug
在虚拟机选项中加入
-Djava.awt.headless=false
我一直在变强!