-2

I have some issues when I do multiple screenshot in a few time: if, for example, I do two screenshot sometimes the second screenshot is the same of the first one.

This is my code:

public static void main(String[] args) {
    BufferedImage screenshot = screen();
    save_screen(screenshot,"title1");
    //some instructions
    screenshot=screen();
    save_screen(screenshot,"title2");
}

private static BufferedImage screen(){
    BufferedImage image=null;
    try {
        image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ImageIO.write(image, "png", new File("/screenshot.png"));
    } catch (HeadlessException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (AWTException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return image;
}

private static void save_screen(BufferedImage image,String title){
    File output = new File("C:\\Users\\MyPC\\Desktop\\" + title + ".png");
    File dir = output.getParentFile();
    if (dir.exists() || dir.mkdirs()) {
    try {
        ImageIO.write(image, "PNG", output);
    } catch (IOException e) {
        e.printStackTrace();
    }    
    } else {
        System.out.println("Bad Path - " + dir);
    }       
}

What can I do to fix this problem?

Thank you in advance!

jww
  • 97,681
  • 90
  • 411
  • 885
Papi44
  • 31
  • 5
  • Add a time interval as low as 0.5 sec . **higher** time or **lower** – Thecarisma Feb 27 '17 at 23:34
  • Personally, I'd avoid writing the screenshot to disk when you capture it, that's an overhead you may not want. You might consider using the same instance of `Robot`, further reduce the overhead. What's the general delay between shots? – MadProgrammer Feb 27 '17 at 23:34

1 Answers1

0

Just add a time interval the code below capture the image exactly after 1 seconds

public static void main(String[] args) {
BufferedImage screenshot = screen();
save_screen(screenshot,"title1");
//some instructions
//Sleep for 1 seconds 
Thread.Sleep(1000);
screenshot=screen();
save_screen(screenshot,"title2"); }
Thecarisma
  • 1,424
  • 18
  • 19