Ooh, Colourful!
Ooh, Colourful!

Take a look at the big green-ish box above this post.

I’m lazy and I haven’t uploaded a featured image. Instead, this custom wordpress theme generates a random colour based on the title of the post, and assigns 1 of 4 possible overlay patterns (in this case, pixellated question marks).

How did I accomplish this, you wonder? It’s quite simply really.

Take this code:

function HSVtoRGB($h, $s, $v) {
	$r = 0; $g = 0; $b = 0;
	
	$tempS = $s / 100;
	$tempV = $v / 100;
	
	$hi = floor($h / 60) % 6;
	
	$f = $h / 60 - floor($h / 60);
	$p = ($tempV * (1 - $tempS));
	$q = ($tempV * (1 - $f * $tempS));
	$t = ($tempV * (1 - (1 - $f) * $tempS));
	
	switch($hi) {
		case 0: $r = $tempV; $g = $t; $b = $p; break;
		case 1: $r = $q; $g = $tempV; $b = $p; break;
		case 2: $r = $p; $g = $tempV; $b = $t; break;
		case 3: $r = $p; $g = $q; $b = $tempV; break;
		case 4: $r = $t; $g = $p; $b = $tempV; break;
		case 5: $r = $tempV; $g = $p; $b = $q; break;
	}	
	return array(
		round($r * 255),
		round($g * 255),
		round($b * 255)
	);
}

Ported from here.

Basically, when fed three numbers for hue (0-360), saturation (0-100), and value (0-100) it generates an RGB colour. If I use pre-coded values for saturation and value, and let it auto-generate the value for the hue, I get a relatively stable set of colours. This means my auto-generated colour will always match my theme.

To get the hue, it’s as easy as taking advantage of the mod operator and md5() functions!

$h = preg_replace('/[^0-9]/', '', md5($in)); // Generate number
list($r, $g, $b) = HSVtoRGB($h % 360, 30, 75); // Generate color

By using preg_replace to remove non-numeric characters from the md5 hash of the title, I get a “number” (It’s actually technically a string, but PHP doesn’t care).

Then I mod (%) it with 360, to get a value from 0-359. (The mod operator calculates remainder.)

The final step is simply to echo the css code into the style attribute of your element!

echo "background-color: rgb($r, $g, $b);";

Leave a Comment

Your email address will not be published. Required fields are marked *

Allowed HTML: a abbr acronym b blockquote cite code del em i q strike strong