我知道如何获取位图的各个像素的RGB值。如何获取位图的所有像素的平均RGB值?
答案 0 :(得分:11)
我认为下面的代码可以为您提供准确答案。 获取给定位图的红色,绿色和蓝色值的平均值(像素数)。
Bitmap bitmap = someBitmap; //assign your bitmap here
int redColors = 0;
int greenColors = 0;
int blueColors = 0;
int pixelCount = 0;
for (int y = 0; y < bitmap.getHeight(); y++)
{
for (int x = 0; x < bitmap.getWidth(); x++)
{
int c = bitmap.getPixel(x, y);
pixelCount++;
redColors += Color.red(c);
greenColors += Color.green(c);
blueColors += Color.blue(c);
}
}
// calculate average of bitmap r,g,b values
int red = (redColors/pixelCount);
int green = (greenColors/pixelCount);
int blue = (blueColors/pixelCount);
答案 1 :(得分:2)
如果Bitmap
具有透明度(PNG),那么约翰sakthi的答案无效。我修改了答案,正确获取红色/绿色/蓝色平均值,同时考虑透明像素:
/**
* Calculate the average red, green, blue color values of a bitmap
*
* @param bitmap
* a {@link Bitmap}
* @return
*/
public static int[] getAverageColorRGB(Bitmap bitmap) {
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
int size = width * height;
int pixelColor;
int r, g, b;
r = g = b = 0;
for (int x = 0; x < width; ++x) {
for (int y = 0; y < height; ++y) {
pixelColor = bitmap.getPixel(x, y);
if (pixelColor == 0) {
size--;
continue;
}
r += Color.red(pixelColor);
g += Color.green(pixelColor);
b += Color.blue(pixelColor);
}
}
r /= size;
g /= size;
b /= size;
return new int[] {
r, g, b
};
}
答案 2 :(得分:1)
您可以将此方法用于此目的:Bitmap.createBitmap
例如:
int[] colors = new int[yourWidth * yourHeight];
Arrays.fill(colors, Color.Black);
Bitmap bitamp = Bitamp.createBitmap(colors, yourWidth, yourHeight, Bitmap.Config.ARGB_8888);
检查拼写错误