0

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?

Rashedul Rough
  • 89
  • 1
  • 10

1 Answers1

0

If rgb1[0] is 8, then Integer.toString(rgb1[0], 16) will return 8, not 08.

Try below:

String xx1 = String.format("#%06X", (0xFFFFFF & swatches.get(x).getRgb()));

where

  • %X will format given int to hexadecimal
  • %6X will format given int to hexadecimal with length 6; If the length of the converted int is shorter than 6, then it'll put some whitespace before it to make it become length of 6
  • %60X same as above, but it'll put some zeros instead of whitespaces
  • #%60X will put # before it
shiftpsh
  • 1,926
  • 17
  • 24