Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get color of pixel LIVE

Tags:

java

colors

mouse

I have a problem with finding the current color under the cursor.

My code:

import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;

public class Test {
    public static void main(String[] args) throws Exception {
        PointerInfo pointer;
        pointer = MouseInfo.getPointerInfo();
        Point coord = pointer.getLocation();

        Robot robot = new Robot();
        robot.delay(2000);

        while(true) {
            coord = MouseInfo.getPointerInfo().getLocation();       
            Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getX());
            if(color.getGreen() == 255 && color.getBlue() == 255 && color.getRed() == 255) {
                System.out.println("WHITE FOUND");
            }
            robot.delay(1000);
        }
    }
}

When I run it, even when I hold my mouse on the gray area, I am getting “WHITE FOUND WHITE FOUND” message.

What can be the problem? Can you guys test if it does not work for you also?

Added Picture: I am holding my cursor on Eclipse gray area but getting “WHITE FOUND” message.

enter image description here

like image 676
Jaanus Avatar asked Apr 28 '11 21:04

Jaanus


People also ask

How to check color of pixel?

Use the ColorSync Utility calculator to get the color values of a pixel on your screen. In the ColorSync Utility app on your Mac, click Calculator in the toolbar of the ColorSync Utility window. Click the magnifying glass , then move your pointer over an area on the screen that you want to examine.

How to get pixel color in c++?

You can use GetDC on the NULL window to get a device context for the whole screen, and can follow that up with a call to GetPixel : HDC dc = GetDC(NULL); COLORREF color = GetPixel(dc, x, y); ReleaseDC(NULL, dc);


1 Answers

I think the problem is you are using getX twice instead of getX and getY

Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getX())

Should be

Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getY())
like image 123
MBU Avatar answered Sep 28 '22 08:09

MBU