Saturday, July 7, 2012

Change RGB to a specific luminance


Perl code to create an RGB from a word/text entry (this is NOT the same as RGB "word colors", such as "blue" or "white")

use Digest::MD5 qw(md5_hex);
my $str = substr( md5_hex("test"), 0, 6);
print "RGB: " . $str."\n";
print "luminance:" . (0.2126*hex(substr($str,0,2)) + 0.7152*hex(substr($str,2,2)) +0.0722*hex(substr($str,4,2)));

This luminance scale is 0-255 (black to white). Divide by 256 for the percentage that you see in online color pickers.

What's with the luminance?
Ideally, you should have 3:1 or even 5:1 contrast to read text, but what do you do when the color is (somewhat) randomly generated and you want to be sure text is legible on the color?

For my purposes, I'm choosing white text on color.
A good cutoff for luminance is about a value of 85.

Based upon the above ratios, if you want to keep the same color (ish), for every 1 point change in green, you'll change red 3.364 (or about 3) points and change blue 9.9058 (or about 10) points. The change in luminance for this iteration is 0.2126*3.3640+0.7152*1+0.0722*9.9058 or 2.14558516 (roughly, 2) luminance units.

Given a luminance x (if given in percent, multiply 256), to achieve luminance y, a way to accomplish that is to take the luminance difference (y-x) and divide by 2.1456 to obtain the change in value of green.

Multiply the resulting change in green by 3.364 to get the change in red and by 9.9058 to get the change in blue to achieve the color with the new luminance.

The code below only executes in your browser and does not send to anyone.
It implements javascript md5
What color is your name?
In my trials, the results seem to be mostly green. If you don't like a given pallet for words, just change your offset for md5. I'm starting on the first character, but it can be shifted practically anywhere down the 32-character MD5 result.

Why MD5? Because it's reasonably assumed to be unique *enough* between random sources. I'm not using it for cryptography, here. This is just used for hex number generation.
<script language="JavaScript" type="text/javascript">
<!--
function sc(el) {
 var dest=document.getElementById('colorme');
 var dest2=document.getElementById('colorme2');
 dest.style.backgroundColor='#'+el;
 dest2.style.backgroundColor='#'+el;
 var lum = 0.2126*parseInt(el.substring(0,2), 16) + 0.7152*parseInt(el.substring(2,4),16) + 0.0722*parseInt(el.substring(4,6),16);
 dest.value=el + " lum:" + lum;
 dest2.value=el + " lum:" + lum;
}
//-->
</script>
<form>
<input type="text" style="width:18em;" onclick="this.value=''" onchange="sc(hex_md5(this.value).substring(0,6))" value="type something and click outside">
<input type="text" id="colorme">
<input type="text" style="color:white" id="colorme2">
</form>

No comments:

Blog Archive