I am trying to get all the colors or dominant colors from an image. Below is the code i have tried.
public ArrayList<String> getDominantColorFromImage(Bitmap bitmap)
{
ArrayList<String> mArr = new ArrayList<>();
List<Palette.Swatch> swatchesTemp = Palette.from(bitmap).generate().getSwatches();
List<Palette.Swatch> swatches = new ArrayList<Palette.Swatch>(swatchesTemp);
Collections.sort(swatches, new Comparator<Palette.Swatch>() {
@Override
public int compare(Palette.Swatch swatch1, Palette.Swatch swatch2) {
return swatch2.getPopulation() - swatch1.getPopulation();
}
});
int x=0;
do{
int[] rgb1 = getRGBArr(swatches.get(x).getRgb());
Log.d("LogImgcolor", "" + rgb1);
//String xx1= Integer.toHexString(rgb1[0]) + Integer.toHexString(rgb1[1]) + Integer.toHexString(rgb1[2]);
String xx1= Integer.toString(rgb1[0], 16) + Integer.toString(rgb1[1], 16) + Integer.toString(rgb1[2], 16);
mArr.add(xx1);
x++;
}while( x < swatches.size());
return mArr;
}
public static int[] getRGBArr(int pixel) {
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
return new int[]{red, green, blue};
}
and to show each color i am simply adding "#" with the color code string. Below is the code:
String colrCode = "#"+ _eachColorCode;
mImgVw.setBackgroundColor(Color.parseColor(colrCode));
But the problem is that its sometimes showing errors , specially when any value in the returned arraylist of color string becomes something like-"#10a010" or "#8a08" or "#10a08".
how to fix it? Is there any better option to get the colors from a image?