views:

115

answers:

3

The background color for one of my pages is set pulled from the background color the users set as their twitter background color. I have a page that has a rounded box with a black border. The border doesnt look good if the background color is dark, so i'd like to remove the border of the background is darker than an arbitrary hex color.

The way I was thinking about doing this was using a regex to pull the 3 RGB values and summing them, and comparing that to my reference color. Is there a better, way to accomplish this?

+4  A: 

You could write a function that converts between RGB and HSL or HSV, and use the lightness or brightness value.

Wikipedia has the math for HSV -> RGB conversion, but not the other way.

http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB

You could also probably pull some JS from this page.

http://www.csgnetwork.com/csgcolorsel4.html

haydenmuhl
HSL/HSV would be better than summing the values and taking an average, as they take the frequency response of the human eye into account. #0c0 and #900 look closer in brightness than #0c0 and #c00, for example. Just summing the values would not be a way forward, because then #990000 would apparently be as bright as #333333.
Dave
Marcel Korpel
+1  A: 

You may also need take in account perceptual brightness of colors (i.e. bright-blue #0000FF looks much darker than bright-red #FF0000 which in turn is much-much darker than #00FF00).

So I'd split the color value into separate bytes and then multiply each by some coefficient:

function getPerceptualBrightness(color) {
  var r = parseInt(color.substring(0,2),16);
  var g = parseInt(color.substring(2,4),16);
  var b = parseInt(color.substring(4,6),16);

  return r*2 + g*3 + b;
}

var green_b = getPerceptualBrightness('00A000');
var blue_b = getPerceptualBrightness('0000FF');

if (green_b > blue_b) 
{ 
    alert("Green is brighter though it's numerical value is smaller"); 
}

This may be less precise than converting to HSL but the latter feels like an overkill for the task...

Sergey
A: 

If the rounded corners are images, this is better treated as a photoshop problem. Save for web/png-24/transparency dither.

If I understand your problem correctly it's not just an issue of light and dark but of hue too. Those corners are dithered to a background that doesn't match these alternate ones. By that I mean the rounded edges are slowly faded from the border to the background color so the jagged pixel edges don't appear to be as jarring.

An arbitrary light/dark solution where you average the three and compare would only work well with fairly extreme lights and darks I would imagine but with a png transparency dither they'll soft-blend into any background automatically. There are workarounds for IE 6 if you have to support it.

Erik Reppen
no images, im just using the css properties
culov