我正在制作一个截取屏幕截图的程序,我想要拥有它,以便我有一个带有 Action 监听器的 JButton,当按下它时,它会将图像保存到某个文件夹中,如果该文件夹尚不存在,则会创建该文件夹。
这是我认为我应该做的:
@Override
public void actionPerformed(ActionEvent arg0) {
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
try {
ImageIO.write(shot, "JPG", dir);
} catch (IOException e) {
e.printStackTrace();
}
}
});
我认为这与我的File dir = new File
有关,并且我没有保存到正确的位置。
这是我的机器人
截取的屏幕截图:
try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
} catch (HeadlessException e1) {
e1.printStackTrace();
} catch (AWTException e1) {
e1.printStackTrace();
}
最佳答案
据我所知,问题在于这两行......
File dir = new File("C://SnippingTool+/" + date.getDay());
dir.mkdirs();
这现在意味着您尝试写入的输出是一个目录,当 ImageIO
需要一个文件时,这将失败...
而是尝试类似...
File output = new File("C://SnippingTool+/" + date.getDay() + ".jpg");
File dir = output.getParentFile();
if (dir.exists() || dir.mkdirs()) {
try {
ImageIO.write(shot, "JPG", output);
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Bad Path - " + dir);
}
关于java - 如何用java保存我的屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17625976/