Bitmap version of RGB search in java

I have the following method that gets the rgb value and classifies it using a smaller palette:

private static int roundToNearestColor( int rgb, int nrColors )
    {
        int red = ( rgb >> 16 ) & 0xFF;
        int green = ( rgb >> 8 ) & 0xFF;
        int blue = ( rgb & 0xFF );
        red = red - ( red % nrColors );
        green = green - ( green % nrColors );
        blue = blue - ( blue % nrColors );
        return 0xFF000000 | ( red << 16 ) | ( green << 8 ) | ( blue );
    }

The code that annoys me is

red = red - ( red % nrColors );
green = green - ( green % nrColors );
blue = blue - ( blue % nrColors );

I am sure that there is an alternative bitwise version that will work faster, but since my bitwise arithmetic is a little rusty, I find it difficult to find such an expression. Any help or comments would be appreciated.

+3
source share
1 answer

If it nrColorsalways matters 2:

private static int roundToNearestColor( int rgb, int nrColors )
{
    if (Integer.bitCount(nrColors) != 1) {
        throw new IllegalArgumentException("nrColors must be a power of two");
    }
    int mask = 0xFF & (-1 << Integer.numberOfTrailingZeros(nrColors));
    int red = ( rgb >> 16 ) & mask;
    int green = ( rgb >> 8 ) & mask;
    int blue = ( rgb & mask );
    return 0xFF000000 | ( red << 16 ) | ( green << 8 ) | ( blue );
}
+1
source

Source: https://habr.com/ru/post/1787478/


All Articles