Skip to content

Instantly share code, notes, and snippets.

@animsh
Created December 19, 2020 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save animsh/9acdc97e77288ff963f64311b3d9f1cf to your computer and use it in GitHub Desktop.
Save animsh/9acdc97e77288ff963f64311b3d9f1cf to your computer and use it in GitHub Desktop.
Pick dominant color from bitmap
public static int getDominantColor(Bitmap bitmap) {
if (bitmap == null) {
return Color.TRANSPARENT;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int size = width * height;
int pixels[] = new int[size];
//Bitmap bitmap2 = bitmap.copy(Bitmap.Config.ARGB_4444, false);
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
int color;
int r = 0;
int g = 0;
int b = 0;
int a;
int count = 0;
for (int i = 0; i < pixels.length; i++) {
color = pixels[i];
a = Color.alpha(color);
if (a > 0) {
r += Color.red(color);
g += Color.green(color);
b += Color.blue(color);
count++;
}
}
r /= count;
g /= count;
b /= count;
r = (r << 16) & 0x00FF0000;
g = (g << 8) & 0x0000FF00;
b = b & 0x000000FF;
color = 0xFF000000 | r | g | b;
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment