Java 如何在Android上获得位图的平均RGB值?
我知道如何获得位图各个像素的RGB值。如何获得位图所有像素的平均RGB值?为此,可以使用此方法: 例如:Java 如何在Android上获得位图的平均RGB值?,java,android,Java,Android,我知道如何获得位图各个像素的RGB值。如何获得位图所有像素的平均RGB值?为此,可以使用此方法: 例如: int[] colors = new int[yourWidth * yourHeight]; Arrays.fill(colors, Color.Black); Bitmap bitamp = Bitamp.createBitmap(colors, yourWidth, yourHeight, Bitmap.Config.ARGB_8888); 检查打字错误我想下面的代码是给你的确切答案
int[] colors = new int[yourWidth * yourHeight];
Arrays.fill(colors, Color.Black);
Bitmap bitamp = Bitamp.createBitmap(colors, yourWidth, yourHeight, Bitmap.Config.ARGB_8888);
检查打字错误我想下面的代码是给你的确切答案。 获取给定位图的红色、绿色和蓝色值的平均值(像素数)
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);
Bitmap Bitmap=someBitmap//在此处指定位图
int redColors=0;
int绿色=0;
int蓝色=0;
int pixelCount=0;
对于(int y=0;y
如果位图具有透明度(PNGs),则john 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
};
}
/**
*计算位图的平均红、绿、蓝颜色值
*
*@param位图
*{@link位图}
*@返回
*/
公共静态int[]getAverageColorRGB(位图){
final int width=bitmap.getWidth();
final int height=bitmap.getHeight();
整数大小=宽度*高度;
int像素颜色;
int r,g,b;
r=g=b=0;
对于(int x=0;x
Klaus66我有一个位图,我想从该位图中获取RGB值。ImageView ImageView=((ImageView)v);位图位图=((BitmapDrawable)imageView.getDrawable()).getBitmap();int pixel=bitmap.getPixel(x,y);int redValue=Color.red(像素);int blueValue=颜色。蓝色(像素);int greenValue=颜色。绿色(像素);对于这里,获取指定像素的RGB值,但我需要获取孔、位图.Red=?、位图.Green=?、位图.Blue=?。位图由像素组成。它没有自己的R、G、B或Alpha值!这就是为什么我不明白这个问题的意思。也许,您需要所有像素的所有红色、绿色和蓝色的平均值?就像那样,RGB值的平均值。对于非常大的图像,您可能需要使用long
ForredColors
和friends来避免整数过载。是的,正确的Kevin,应该是避免int,使用非常大的图像时。这将导致ArrayIndexOutOfBoundsException。颜色数组中至少需要width*height元素。@qed,确实需要。谢谢你的反馈