Skip to content

Instantly share code, notes, and snippets.

@RyanNutt
Created August 1, 2019 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanNutt/ea02e838e3419893b1edddbcac9c1dd2 to your computer and use it in GitHub Desktop.
Save RyanNutt/ea02e838e3419893b1edddbcac9c1dd2 to your computer and use it in GitHub Desktop.
Get a "web safe" color based on string contents in PHP

Get color for string in PHP

I've needed to do this a couple of times, so I guess it's time to save it as a Gist for next time.

What I needed was a way to calculate a color based on string contents, where the same string would always generate the same color. I also wanted the colors generated to be part of the web safe palette. Not that there's any reason to stay in that palette for browsers now, but I wanted to keep the possible palette relatively small and have colors that generally look okay together. The math behind the web safe palette made it pretty easy.

As it works out, all of the web safe colors are multiples of 51. We'll need that bit of trivia in a second...

First thing I did was get the md5 hash of the string so the code has a string of hexadecimal characters to work with. The first 2 hex characters become the red value, the next 2 are green, and the next 2 are blue. Those are then converted to decimal to make the math easier.

Using a formula that I found on Stack Overflow each number is rounded to the nearest multiple of 51. Since the largest hex value would be ff I didn't have to worry about overflowing.

A bit of sprintf to format, and it'll kick out the hex code that I needed.

If I hadn't wanted to stay within the web safe palette, this would have been much shorter. I would have just taken the first 6 characters from the md5 hash and added a # to the front.

<?php
function websafe( $string ) {
$string = md5( $string );
$red = hexdec( substr( $string, 0, 2 ) );
$green = hexdec( substr( $string, 2, 2 ) );
$blue = hexdec( substr( $string, 4, 2 ) );
$multiple = 51;
$red = $red + ($multiple / 2);
$red -= $red % $multiple;
$green = $green + ($multiple / 2);
$green -= $green % $multiple;
$blue = $blue + ($multiple / 2);
$blue -= $blue % $multiple;
return sprintf( "#%02x%02x%02x", $red, $green, $blue );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment