Created
April 9, 2015 16:28
-
-
Save httnn/a6ab15cbba9c82a5065d to your computer and use it in GitHub Desktop.
Calculate average color of Android Bitmap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
pixelSpacing tells how many pixels to skip each pixel. | |
If pixelSpacing > 1: the average color is an estimate, but higher values mean better performance | |
If pixelSpacing == 1: the average color will be the real average | |
If pixelSpacing < 1: the method will most likely crash (don't use values below 1) | |
*/ | |
public int calculateAverageColor(android.graphics.Bitmap bitmap, int pixelSpacing) { | |
int R = 0; int G = 0; int B = 0; | |
int height = bitmap.getHeight(); | |
int width = bitmap.getWidth(); | |
int n = 0; | |
int[] pixels = new int[width * height]; | |
bitmap.getPixels(pixels, 0, width, 0, 0, width, height); | |
for (int i = 0; i < pixels.length; i += pixelSpacing) { | |
int color = pixels[i]; | |
R += Color.red(color); | |
G += Color.green(color); | |
B += Color.blue(color); | |
n++; | |
} | |
return Color.rgb(R / n, G / n, B / n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment