0

I am looking for a class in Java that gives me possibility to check if e.g. pixel (x,y) is red or average color from selected screen area is X. Is there a class that supports it? If no, i'd try to create that kind of class on my own. Does Java have tools that support such operations?

Czachodym
  • 245
  • 2
  • 13
  • See https://stackoverflow.com/questions/19688104/fast-pixel-search-in-java and https://stackoverflow.com/questions/8350073/getting-pixel-information-from-the-screen-quickly – Nosrep Feb 08 '20 at 19:32

1 Answers1

1

You can use the Robot class with a simple calculation to check if the color is close to the color you are looking for

package test;

import java.awt.Color;
import java.awt.Robot;
import java.awt.AWTException;

public class main {

    static final Color RED_COLOR = new Color(255, 0, 0);

    private static boolean colorsAreClose(Color color1, Color color2, int threshold) {
        int r = (int) color1.getRed() - color2.getRed(), g = (int) color1.getGreen() - color2.getGreen(),
                b = (int) color1.getBlue() - color2.getBlue();
        return (r * r + g * g + b * b) <= threshold * threshold;
    }

    public static void main(String[] args) {
        Color pixelColor = null;
        try {
            Robot robot = new Robot();
            pixelColor = robot.getPixelColor(500, 500);
            System.out.println(String.format("Red %d, Green %d, Blue %d", pixelColor.getRed(), pixelColor.getGreen(),
                    pixelColor.getBlue()));

        } catch (AWTException e) {
            e.printStackTrace();
            return;
        }

        boolean isRedPixel = colorsAreClose(pixelColor, RED_COLOR, 50);
        System.out.println(isRedPixel ? "Pixel is red" : "Pixel is not red");
    }

}
Black0ut
  • 1,642
  • 14
  • 28