Friday, February 11, 2011

SHARE - How to calculate how much brighness from color

My client ask me about how to make text black or white color base on background color for that text.

example:

- background color black, color of text is white
- background color white, color of text is black
- background color yellow, color of text is black
- background color dark-purple, color of text is white

I think I need to calculate how much brighness from background color that used.

After googling I found this formula for calculating brighness.

brightness = sqrt( .241 R2 + .691 G2 + .068 B2 )

R = red color (decimal)
G = green color (decimal)
B = blue color (decimal)

example:
   
background color : EA0516, text color : FFFFFF
backgorund color : FFFF00, text color : 000000

on my model

class model

def self.calculate_brightness(color) #format color on hex without #, example FFFFFF
r = color[0..1].hex
g = color[2..3].hex
b = color[4..5].hex
value = Math.sqrt(r * r * 0.241 + g * g * 0.691 + b * b * 0.068)
(value < 130 ? 'FFFFFF' : '000000')
end

end

You can see more information here
http://alienryderflex.com/hsp.html
http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx

No comments:

Post a Comment