Question

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?

Was it helpful?

Solution

Actually -1 means that all bits are set to 1. So, you will have plain white instead of black. That seems valid, to me. Since you told you were using Mac OS X, this could be right, because, look at the top left corner, it looks like this:

enter image description here enter image description here

There might be some plain white there in the corner. The second picture contains perfectly plain white. This can be achieved by setting a white background (at least, white in the corner) and translucent top menu bar enabled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top