Search code examples
javaandroidkotlinimage-processingcolors

How can I get the average color of an image?


I want to be able to take an image and find out what is its average color, meaning if the image is half black and half white, I would get something in-between... some shade of gray. It could be the most frequent single color or median. Any average will do.

How can I do this in Android?


Solution

  • Bitmap bitmap = someFunctionReturningABitmap();
    long redBucket = 0;
    long greenBucket = 0;
    long blueBucket = 0;
    long pixelCount = 0;
    
    for (int y = 0; y < bitmap.getHeight(); y++)
    {
        for (int x = 0; x < bitmap.getWidth(); x++)
        {
            Color c = bitmap.getPixel(x, y);
    
            pixelCount++;
            redBucket += Color.red(c);
            greenBucket += Color.green(c);
            blueBucket += Color.blue(c);
            // does alpha matter?
        }
    }
    
    Color averageColor = Color.rgb(redBucket / pixelCount,
                                    greenBucket / pixelCount,
                                    blueBucket / pixelCount);