如何在 Java 中保存我的屏幕截图 [英] How To Save My Screenshot in java

查看:32
本文介绍了如何在 Java 中保存我的屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个截取屏幕截图的程序,我想拥有它,以便我有一个带有动作侦听器的 JButton,按下时它将图像保存到某个文件夹中,如果该文件夹尚不存在,则它会生成.

I'm making a program that takes a screenshot and I want to have it so that i have a JButton with an actionlistener that when pressed it saves the image to a certain folder that if does not already exists it makes.

这是我认为我应该做的:

here is what I thought I should do:

@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 和我没有保存到正确的位置有关.

I think it has something to do with my File dir = new File and that I am not saving to to the right place.

这是我的 Robot 截图:

try {
shot = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    } catch (HeadlessException e1) {
        e1.printStackTrace();
    } catch (AWTException e1) {
        e1.printStackTrace();
    }

推荐答案

问题,在我看来是这两行...

The problem, as I see it is with these two lines...

File dir = new File("C://SnippingTool+/" +  date.getDay());
dir.mkdirs();

这现在意味着您尝试写入的输出是一个目录,当 ImageIO 需要一个文件时,这将失败...

This now means that the output you are trying to write to is a directory, when ImageIO is expecting a file, this will fail...

而是尝试类似...

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 中保存我的屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆