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

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

问题描述

我正在制作一个需要截图的程序,所以我想拥有一个带有动作监听器的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();
}


解决方案

问题,如我所见就是这两行...

 文件目录=新文件( C:// SnippingTool + / +日期。 getDay()); 
dir.mkdirs();

现在这表示当<$ c $时,您要写入的输出是目录c> ImageIO 正在等待文件,这将失败...



相反,请尝试类似...

 文件输出=新文件( C:// SnippingTool + / + date.getDay()+ .jpg); 
文件目录= output.getParentFile();
if(dir.exists()|| dir.mkdirs()){
try {
ImageIO.write(shot, JPG,输出);
} catch(IOException e){
e.printStackTrace();
}
} else {
System.out.println( Bad Path- + dir);
}


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();
}

    }

});

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

Here is my Robot taking a screenshot:

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();

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

Instead try something like...

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天全站免登陆