I have the code:
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bi = robot.createScreenCapture(area);
int[] pixels = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
System.out.println(pixels[0*4]);
where "robot" is an instance of the class "Robot" created elsewhere.
Sometimes, this code outputs "-1", meaning that the first pixel is, somehow, invalid. Other times, this code outputs a number like "-1828129198" which is expected behavior.
Here is where things get weird. I have this piece of code, later in the same class:
private static void DebugImage(BufferedImage bi)
{
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JLabel(new ImageIcon(bi)));
frame.pack();
frame.setVisible(true);
}
When I first tested the first piece of code today, I got -1 as output. However, when I changed the original piece of code to include a call to DebugImage, as follows:
Rectangle area = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage bi = robot.createScreenCapture(area);
DebugImage(bi);
int[] pixels = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData();
System.out.println(pixels[0*4]);
I suddenly stopped getting "-1", and finally got some valid data! The kicker? When I removed the call to DebugImage, putting it back into its original form, the code did not stop working, and continued to successfully not return -1. (NOTE: I am using Eclipse)
I imagine this must be thread related, or is perhaps some kind of memory management issue, but to be honest, I have very little indication as to what is going on.
Does anyone have any experience with using Robot for screenshot capture, or any ideas on how to prevent this?