Stack Overflow archive
2 score

How to get average RGB value of Bitmap on Android?

score
2
question views
8.6K
license
CC BY-SA 3.0

The answer from john sakthi does not work correctly if the Bitmap has transparency (PNGs). I modified the answer for correctly getting the red/green/blue averages while accounting for transparent pixels:

java
/**
 * Calculate the average red, green, blue color values of a bitmap
 *
 * @param bitmap
 *            a {@link Bitmap}
 * @return
 */
public static int[] getAverageColorRGB(Bitmap bitmap) {
    final int width = bitmap.getWidth();
    final int height = bitmap.getHeight();
    int size = width * height;
    int pixelColor;
    int r, g, b;
    r = g = b = 0;
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            pixelColor = bitmap.getPixel(x, y);
            if (pixelColor == 0) {
                size--;
                continue;
            }
            r += Color.red(pixelColor);
            g += Color.green(pixelColor);
            b += Color.blue(pixelColor);
        }
    }
    r /= size;
    g /= size;
    b /= size;
    return new int[] {
            r, g, b
    };
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.