在Android @drawable中查找图像的主色

时间:2011-12-12 07:39:26

标签: android colors bitmap drawable

如果使用Windows 7,您可以理解为什么我要在图像中找到主色。当您将鼠标悬停在任务栏中的某个程序上时,该特定程序的背景会根据最主要的颜色而变化。图标。我已经注意到其他程序中使用的这种技术,但不能记住它们。

我可以看到这对我用于开发应用程序的一些UI技术很有帮助,我想知道如何从Android可绘制资源中找到最常见的颜色。

8 个答案:

答案 0 :(得分:63)

在Android 5.0 Lollipop中,添加了一个类来帮助从Bitmap中提取有用的颜色。 android.support.v7.graphics中的Palette类可以提取以下颜色:

  • 活力
  • 充满活力的黑暗
  • 充满活力的光明
  • 静音
  • Muted Dark
  • 柔和的光线

此Android培训页面提供了使用该课程所需的所有详细信息(我在Android Studio中自己尝试了这一点并且非常简单):http://developer.android.com/training/material/drawables.html#ColorExtract

引用:

  

Android支持库r21及更高版本包括Palette   class,它允许您从图像中提取突出的颜色。至   提取这些颜色,将一个Bitmap对象传递给Palette.generate()   加载图像的后台线程中的静态方法。如果   你不能使用那个线程,调用Palette.generateAsync()方法和   提供一个听众。*

     

您可以使用吸气剂从图像中检索突出的颜色   Palette类中的方法,例如Palette.getVibrantColor。

     

要在项目中使用Palette类,请添加以下Gradle   依赖于您应用的模块:

dependencies {
    ...
    compile 'com.android.support:palette-v7:21.0.+'
}

*如果您需要使用generateAsync(),请按以下步骤操作:

Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
    public void onGenerated(Palette palette) {
        // Do something with colors...
    }
});

编辑: 由于问题是如何从可绘制资源中提取颜色,因此首先必须将drawable转换为位图以使用我所描述的技术。幸运的是,使用BitmapFactory非常简单:

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                       R.drawable.icon_resource);`

答案 1 :(得分:26)

还有另一种解决方案,它更具近似性,但如果您不想长时间搜索颜色,它可以完成这项工作。

public static int getDominantColor(Bitmap bitmap) {
    Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 1, 1, true);
    final int color = newBitmap.getPixel(0, 0);
    newBitmap.recycle();
    return color;
}

答案 2 :(得分:7)

此类迭代Bitmap并返回最主要的颜色。 请在必要时随意清理代码。

public class ImageColour {

String colour;


public ImageColour(Bitmap image) throws Exception {

     int height = image.getHeight();
     int width = image.getWidth();

     Map m = new HashMap();

        for(int i=0; i < width ; i++){

            for(int j=0; j < height ; j++){

                int rgb = image.getPixel(i, j);
                int[] rgbArr = getRGBArr(rgb);                

                if (!isGray(rgbArr)) {   

                        Integer counter = (Integer) m.get(rgb);   
                        if (counter == null)
                            counter = 0;
                        counter++;                                
                        m.put(rgb, counter);       

                }                
            }
        }        

        String colourHex = getMostCommonColour(m);
    }



    public static String getMostCommonColour(Map map) {

        List list = new LinkedList(map.entrySet());
        Collections.sort(list, new Comparator() {
              public int compare(Object o1, Object o2) {

                return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());

              }

        });    

        Map.Entry me = (Map.Entry )list.get(list.size()-1);
        int[] rgb= getRGBArr((Integer)me.getKey());

        return Integer.toHexString(rgb[0])+" "+Integer.toHexString(rgb[1])+" "+Integer.toHexString(rgb[2]);        
    }    


    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};

  }

    public static boolean isGray(int[] rgbArr) {

        int rgDiff = rgbArr[0] - rgbArr[1];
        int rbDiff = rgbArr[0] - rgbArr[2];

        int tolerance = 10;

        if (rgDiff > tolerance || rgDiff < -tolerance) 
            if (rbDiff > tolerance || rbDiff < -tolerance) { 

                return false;

            }                

        return true;
    }


public String returnColour() {

    if (colour.length() == 6) {
        return colour.replaceAll("\\s", "");
    } else {
        return "ffffff";
    }
}

只需调用十六进制即可     returnColour();

答案 3 :(得分:4)

我写了自己的方法来获得主色:

方法1 (我的技术)

  1. 缩小为ARGB_4444色彩空间
  2. 计算单个RGB元素的最大出现次数并获得3个不同的最大值
  3. 将最大值与主色RGB颜色相结合

    public int getDominantColor1(Bitmap bitmap) {
    
    if (bitmap == null)
        throw new NullPointerException();
    
    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);
    
    bitmap2.getPixels(pixels, 0, width, 0, 0, width, height);
    
    final List<HashMap<Integer, Integer>> colorMap = new ArrayList<HashMap<Integer, Integer>>();
    colorMap.add(new HashMap<Integer, Integer>());
    colorMap.add(new HashMap<Integer, Integer>());
    colorMap.add(new HashMap<Integer, Integer>());
    
    int color = 0;
    int r = 0;
    int g = 0;
    int b = 0;
    Integer rC, gC, bC;
    for (int i = 0; i < pixels.length; i++) {
        color = pixels[i];
    
        r = Color.red(color);
        g = Color.green(color);
        b = Color.blue(color);
    
        rC = colorMap.get(0).get(r);
        if (rC == null)
            rC = 0;
        colorMap.get(0).put(r, ++rC);
    
        gC = colorMap.get(1).get(g);
        if (gC == null)
            gC = 0;
        colorMap.get(1).put(g, ++gC);
    
        bC = colorMap.get(2).get(b);
        if (bC == null)
            bC = 0;
        colorMap.get(2).put(b, ++bC);
    }
    
    int[] rgb = new int[3];
    for (int i = 0; i < 3; i++) {
        int max = 0;
        int val = 0;
        for (Map.Entry<Integer, Integer> entry : colorMap.get(i).entrySet()) {
            if (entry.getValue() > max) {
                max = entry.getValue();
                val = entry.getKey();
            }
        }
        rgb[i] = val;
    }
    
    int dominantColor = Color.rgb(rgb[0], rgb[1], rgb[2]);
    
    return dominantColor;
     }
    
  4. 方法2 (旧技术)

    1. 缩小为ARGB_4444色彩空间
    2. 计算每种颜色的出现次数并找出最大颜色为主色

      public int getDominantColor2(Bitmap bitmap) {
      if (bitmap == null)
          throw new NullPointerException();
      
      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);
      
      bitmap2.getPixels(pixels, 0, width, 0, 0, width, height);
      
      HashMap<Integer, Integer> colorMap = new HashMap<Integer, Integer>();
      
      int color = 0;
      Integer count = 0;
      for (int i = 0; i < pixels.length; i++) {
          color = pixels[i];
          count = colorMap.get(color);
          if (count == null)
              count = 0;
          colorMap.put(color, ++count);
      }
      
      int dominantColor = 0;
      int max = 0;
      for (Map.Entry<Integer, Integer> entry : colorMap.entrySet()) {
          if (entry.getValue() > max) {
              max = entry.getValue();
              dominantColor = entry.getKey();
          }
      }
      return dominantColor;
      }
      

答案 4 :(得分:2)

循环遍历所有像素的颜色数据并平均颜色值,忽略任何灰色或透明阴影。我相信这是微软基于最近的博客文章在Windows 7中所做的事情。

修改
博文:http://blogs.msdn.com/b/oldnewthing/archive/2011/12/06/10244432.aspx

此链接显示了Chrome如何选择主色也可能会有所帮助。 http://www.quora.com/Google-Chrome/How-does-Chrome-pick-the-color-for-the-stripes-on-the-Most-visited-page-thumbnails

答案 5 :(得分:2)

添加到依赖项

implementation 'androidx.palette:palette:1.0.0'

和..

 AppCompatImageView imageView = findViewById(R.id.image_view);

 Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
 Palette.from(bitmap).generate(palette -> {
      int vibrant = palette.getVibrantColor(0x000000); // <=== color you want
      int vibrantLight = palette.getLightVibrantColor(0x000000);
      int vibrantDark = palette.getDarkVibrantColor(0x000000);
      int muted = palette.getMutedColor(0x000000);
      int mutedLight = palette.getLightMutedColor(0x000000);
      int mutedDark = palette.getDarkMutedColor(0x000000);
 });

答案 6 :(得分:0)

其他答案都没有为我完成这项工作,我也没有排除问题的原因。

这是我最终使用的:

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;
}

答案 7 :(得分:0)

要从图像中找到 主要 /充满活力/静音的颜色,请使用Palette

导入:

implementation 'androidx.palette:palette:1.0.0'

用法:

    val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image)

    Palette.Builder(bitmap).generate { it?.let {  palette ->
        val dominantColor = palette.getDominantColor(ContextCompat.getColor(context!!, R.color.defaultColor))

        // TODO: use dominant color

    } }