简体   繁体   English

在java中截取屏幕截图并将其保存在桌面上

[英]take a screenshot in java and save it on desktop

I write a code to capture screenshot in java in windows 7. This screenshot is saved in my workspace.我编写了一个代码来在 Windows 7 中用 java 捕获屏幕截图。此屏幕截图保存在我的工作区中。

I want this screenshot to be saved directly to desktop.我希望将此屏幕截图直接保存到桌面。

import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;     
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;

public class FullScreenCaptureExample {

    public static void main(String[] args) {
        try {
            Robot robot = new Robot();
            String format = "jpg";
            String fileName = "FullScreenshot." + format;

            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
            ImageIO.write(screenFullImage, format, new File(fileName));

            System.out.println("A full screenshot saved!");
        } catch (AWTException | IOException ex) {
            System.err.println(ex);
        }
    }
}

You are not using the right file name if you want it to be saved on your desktop.如果您希望将其保存在桌面上,则您没有使用正确的文件名。 It should include the path to your desktop.它应该包括桌面的路径。 Say for example your desktop could be accessed via: C:\\Users\\UserName\\Desktop , then you should replace the statment:例如,您的桌面可以通过以下方式访问: C:\\Users\\UserName\\Desktop ,那么您应该替换以下语句:

String fileName = "FullScreenshot." + format;

with:和:

String deskTopPath = "C:\\Users\\UserName\\Desktop";
String fileName = deskTopPath + "\\" + "FullScreenshot." + format;

Take note: If you want to take and save multiple shots then you should make the file name FullScreenshot unique for each shots.注意:如果你想拍摄并保存多张照片,那么你应该为每张照片设置唯一的文件名FullScreenshot Devise a good strategy to make the FullScreenshot name to be unique (like appending the date time to that string).设计一个好的策略,使FullScreenshot名称唯一(例如将日期时间附加到该字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM