Programming Tips - Java: Is that pixel dark or light?

Date: 2013jun6 Update: 2025sep5 Language: Java Q. Java: Is that pixel dark or light? A. Convert the pixel to the YIQ colorspace. Then large values are light and small are dark. Full working example:
import java.awt.Color; class Demo { static int toYiq(final int r, final int g, final int b) { return ((r * 299) + (g * 587) + (b * 114)) / 1000; } static boolean isDark(final Color color) { final int yiq = toYiq(color.getRed(), color.getGreen(), color.getBlue()); return yiq < 128; } public static void main(String [] args) { final Color color = Color.GREEN; if (isDark(color)) { System.out.println("It is dark"); } else { System.out.println("It is light"); } } }
More info https://en.wikipedia.org/wiki/YIQ "The YIQ system is intended to take advantage of human color-response characteristics."