简体   繁体   中英

Get pixel color in java

I know this is an expensive operation and I already tried to use the robot.getPixelColor() function but it works slow, can only calculate like 5 times in a second.

What I'm saying is that 5 times is too small for what I actually want to do, but 20 should be enough. So I ask you if you can suggest me some optimisations to make to my actual code in order to get this result.

My code is:

while (true) {
    color = robot.getPixelColor(x, y);
    red = color.getRed();
    green = color.getGreen();
    blue = color.getBlue();
    // do a few other operations in constant time
}

I don't know if this would help, but x and y don't change inside the while loop. So it's all the time the same pixel coordinates.

Thanks in advance!

EDIT: The pixel color will be taken from a game which will run at the same time with the java program, it will keep changing. The only thing is that are always the same coordinates.

I'm assuming the color is represented as a 32-bit int encoded as ARGB. In that case, instead of calling a method, you could just do bit masking to extract the colors, and that may end up being faster because you don't waste the overhead of calling a method. I'd recommend doing something like this:

int color = robot.getPixelColor(x,y);
int redBitMask = 0x00FF0000;
int greenBitMask = 0x0000FF00;
int blueBitMask = 0x000000FF;
int extractedRed = (color & redBitMask) >> 16;
int extractedGreen = (color & greenBitMask) >> 8;
int extractedBlue = (color & blueBitMask);

Bit shifting and bitwise operations tend to be very fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM