Java BufferedImage get single pixel brightness

Tobia picture Tobia · Jan 18, 2014 · Viewed 7.6k times · Source

I want to convert coloured image to a monochrome, i thought to loop all pixel, but I don't know how to test if they are bright or dark.

        for(int y=0;y<image.getHeight();y++){
            for(int x=0;x<image.getWidth();x++){
                int color=image.getRGB(x, y);
                // ???how to test if its is bright or dark?
            }
        }

Answer

Boann picture Boann · Jan 18, 2014
int color = image.getRGB(x, y);

// extract each color component
int red   = (color >>> 16) & 0xFF;
int green = (color >>>  8) & 0xFF;
int blue  = (color >>>  0) & 0xFF;

// calc luminance in range 0.0 to 1.0; using SRGB luminance constants
float luminance = (red * 0.2126f + green * 0.7152f + blue * 0.0722f) / 255;

// choose brightness threshold as appropriate:
if (luminance >= 0.5f) {
    // bright color
} else {
    // dark color
}