java - 保存到桌面的图像会覆盖之前的图像

标签 java jsp web-applications screenshot

我在 JSP Web 应用程序中添加了一个功能,用户可以对他正在查看的页面进行屏幕截图,并将图像保存到桌面,当我拍摄另一个屏幕截图时,它会覆盖以前的图像。有什么方法可以递增,以便将其另存为图像,如果我拍摄另一个屏幕截图,它将另存为 image1、image2 等。

执行此任务的代码是

try {
        Robot robot = new Robot();
        BufferedImage screenShot = robot
                .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        String home = System.getProperty("user.home");

        ImageIO.write(screenShot, "JPG", new File(home + "\\Desktop\\i.jpg"));

    } catch (IOException ex) {
        System.out.println(ex.toString());
    }

最佳答案

为此,您首先需要检查桌面中是否已存在同名文件:

boolean check = new File(directory, temp).exists();

如果 booelan 检查为 true,则意味着该文件已存在,并且具有相同的名称。然后,您可以根据需要更改第二个文件的名称(例如,向其中添加数字)!

此外,如果用户想要将文件另存为image3,并且已经有一个以这种方式调用的文件,您可以像这样更改它:

int num;

try {
   num = Integer.parseInt(String.valueOf(string.substring(string.length() - 1)));
   // then change the name of the file that you are saving for example, from "image4" to "image5"
} catch (exception e) {
   // This means that the name of the file you are saving does not finish with a number, so you can simply proceed by adding a "1" as the last character of the string name (containing the name of the file the user wants to save)
}

关于java - 保存到桌面的图像会覆盖之前的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59106184/

相关文章:

java - 无法通过 chrome/firefox 获取请求参数值。与双重转义有关?

c# - mvc.net 4 的管理 UI 界面

java - 如何改进 Apache Wicket 以进行 Groovy 编程?

java - 使用 hibernate 连接两个表

java - 自动生成 key

spring - BindingResult 和 bean 名称 'contact' 的普通目标对象都不能作为请求属性

java - 比 ColorConvertOp 更快的替代品

java - 在 JSP 中将 JavaScript 变量分配给 Java 变量

java - 当 Servlet、JSP 和轻量级 DAO 层可以工作时,为什么要使用 MVC 框架?

visual-studio-2008 - VS 200 8's "转换为网站是什么意思?