Determine if getPixel() value is greater than or less than 50% gray
I am trying to loop throug开发者_JAVA百科h a bitmap and determine if each pixel is lighter or darker than gray using getPixel(). Problem is, I am not sure how to tell whether the value returned by getPixel() is darker or lighter than gray.
Neutral gray is about 0x808080 or R:127, G:127, B:127. How would I need to modify the code below to accurately determine this?
for (var dx:int=0; dx < objectWidth; dx++)
{
for (var dy:int=0; dy < objectHeight; dy++)
{
if (testBmd.getPixel(dx, dy) > GRAY)
{
trace("Lighter than gray!");
} else {
trace("Darker than gray!");
}
}
}
To extend Adam's answer a bit further, you could generate a luminance value using a function like this...
function luminance(myRGB:int):int {
//returns a luminance value between 0 and 255
var R:int = (myRGB / 65536) % 256;
var G:int = (myRGB / 256) % 256;
var B:int = myRGB % 256;
return ((0.3*R)+(0.59*G)+(0.11*B));
}
Then you can test for your 50% grey threshold like this:
if (luminance(testBmd.getPixel(dx, dy)) > 127)
Luminance is the answer - Math needed and explanation here:
http://www.scantips.com/lumin.html
you know how to continue :)
Edit:
on livedocs (livedocs - BitmapData - getPixel32()), you can see in example, how they get r,g,b, values from getPixel32() return value. Maybe you can use i:]
Also, Richard's answer looks like it already does what you need, although if you combine it with example from above - voilla - you've got yourself an luminance comparison :]
精彩评论