3

How exactly does the method getPixelColor(int x,int y) from the Robot class work? I tried this code fragment:

try 
{
     Robot robos = new Robot();
}
catch (AWTException e) 
{

}

for (int i = 0; i < 100; i++)
    robos.getPixelColor(0, 0);

System.out.println("fsadf");

on my PC, which is a core 2 duo, and it took one second or less to execute the print statement. However, when I ran this same code on my laptop, which is a core i3, it took much more time (about 2-3 seconds).

What is the reason behind this? Does it have to do with the screen quality or something like that? How can I solve this problem?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
blenddd
  • 345
  • 1
  • 6
  • 15
  • *it took like 1 sec or less to execute"* A smart VM might realize that loop does (or at least achieves) absolutely nothing, and thereby remove it completely. Or to put that another way, it might not be the hardware but the VMs that are the difference. As general points though. 1) Don't perform premature optimization. 2) If the code does need to be optimized, don't base design decisions on these trivial, irrelevant tests. BTW - AFAIU that code would not even compile, since `robos` is out of scope in the loop. – Andrew Thompson Aug 24 '11 at 13:31

1 Answers1

10

how can i solve this problem?

Don't use the Robot to get the colors pixel by pixel. Use the Robot the create a BufferedImage of the screen. Then you can use the getRGB() method of the BufferedImage to get the int value that represents the color of the pixel. You can then create a Color Object using this int or parse out the red/green/blue values directly.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • and what exactly is wrong with using the robot like im doing? – blenddd Aug 24 '11 at 00:31
  • 2
    There is nothing wrong, its just not very efficient as you have noticed. It is far more efficient to make one system call to create the image than it is to do thousands of systems calls to get the pixels one at a time. – camickr Aug 24 '11 at 00:42
  • mmm so can you show me a small code fragment how exactly to use this getRGB? – blenddd Aug 24 '11 at 00:55
  • 3
    +1 for `createScreenCapture()`. Related examples [here](http://stackoverflow.com/questions/3742731/java-how-to-draw-constantly-changing-graphics). – trashgod Aug 24 '11 at 02:16