Created
December 19, 2020 19:57
-
-
Save animsh/9acdc97e77288ff963f64311b3d9f1cf to your computer and use it in GitHub Desktop.
Pick dominant color from bitmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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