How can I get the average colour of an image

后端 未结 6 571
温柔的废话
温柔的废话 2020-12-07 16:57

I want to be able to take an image and find out what is the average colour. meaning if the image is half black half white, I would get something in between... some shade of

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 17:09

    Building off Dan O's solution, here's a method that automatically takes into account the alpha channel and makes the optimization/ tradeoff of getPixels vs getPixel.

    The cost is memory but the benefit is performance, invocation of a virtual method in a loop that could possibly be run several million times [i.e. an 8MP image has 3,456x2,304 = 7,962,624 pixels]). I've even taken things one step further by removing the looped android.graphics.Color method calls.

    public static int getDominantColor(Bitmap bitmap) {
       if (null == bitmap) return Color.TRANSPARENT;
    
       int redBucket = 0;
       int greenBucket = 0;
       int blueBucket = 0;
       int alphaBucket = 0;
    
       boolean hasAlpha = bitmap.hasAlpha();
       int pixelCount = bitmap.getWidth() * bitmap.getHeight();
       int[] pixels = new int[pixelCount];
       bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
    
       for (int y = 0, h = bitmap.getHeight(); y < h; y++)
       {
           for (int x = 0, w = bitmap.getWidth(); x < w; x++)
           {
               int color = pixels[x + y * w]; // x + y * width
               redBucket += (color >> 16) & 0xFF; // Color.red
               greenBucket += (color >> 8) & 0xFF; // Color.greed
               blueBucket += (color & 0xFF); // Color.blue
               if (hasAlpha) alphaBucket += (color >>> 24); // Color.alpha
           }
       }
    
       return Color.argb(
               (hasAlpha) ? (alphaBucket / pixelCount) : 255,
               redBucket / pixelCount,
               greenBucket / pixelCount,
               blueBucket / pixelCount);
    }
    

提交回复
热议问题