Skip to content

Instantly share code, notes, and snippets.

@httnn
Created April 9, 2015 16:23
Show Gist options
  • Save httnn/b1d772caf76cdc0c11e2 to your computer and use it in GitHub Desktop.
Save httnn/b1d772caf76cdc0c11e2 to your computer and use it in GitHub Desktop.
Calculate brightness of Android Bitmap
/*
Calculates the estimated brightness of an Android Bitmap.
pixelSpacing tells how many pixels to skip each pixel. Higher values result in better performance, but a more rough estimate.
When pixelSpacing = 1, the method actually calculates the real average brightness, not an estimate.
This is what the calculateBrightness() shorthand is for.
Do not use values for pixelSpacing that are smaller than 1.
*/
public int calculateBrightnessEstimate(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 (R + B + G) / (n * 3);
}
public int calculateBrightness(android.graphics.Bitmap bitmap) {
calculateBrightnessEstimate(bitmap, 1);
}
@mylogon341
Copy link

I know this is a bit of an old one, but can ask what sort of range i should see returned from this? In bright images i'm seeing values above 100 and below -100. Darker images seem to be within that range. For now, I am just using Math.abs(), but am not sure what to expect from it. Thanks.

@sagarvasnani
Copy link

sagarvasnani commented Feb 20, 2018

Here, the brightness returned is between 0 and 255, where 0 is returned for a pure black image and 255 for a white one.

@NeighborhoodCoding
Copy link

Thanks, it is awesome, but can you provide the calculation of colorfulness or blur? it uses std of R,G,B but implementing in java is very hard...T.T

@KevinAS28
Copy link

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment