Sunday, August 26, 2012

Converting HTML hex color to RGB value

Hi everyone,
I had to solve a little problem: converting hex color value (like CSS/HTML color code #FFFFFF) to a blender friendly color code (a triplet of float numbers, range(0,1) like (1,1,1)) and back again.

Ok: this is not THE problem, and maybe lots of you will be laughting reading this, but this has been MY BIG problem for 30 minutes. And I've got to thank a lot Alvaro Moe from OpenTechSchool workshops (Berlin), a very skilled Python and Javascript developer who is spending his days at Campus Party Europe with me. So... let's go!




1 - From HTML color to CG color:


Taking this light-blue color HTML hex code #1075f5 is built this way:

# - the identifier
10 - the value for Red channel
75 - the value for Green channel
f5 - the value for Blue channel

Each couple can handle 0-255 value. As standard, if we have one number only we've to add '0' in front of it to keep six element rule. In this example we won't take care of alpha value because it's not handled by 'color picker' element but you can add it easely.

First of all, let's convert a simple HEX couple (the first, RED channel) to a FLOAT number; Javascript gives us a nice instruction in order to do this:
Now we need to map the 0-255 value to a 0-1 scale. Let's divide it for 255:


Let's do it for each channel:

Ok, but <color_picker>.value is a string. I've got to parse it to get the single couples, removing '#' symbol and slicing the couples:

  • splitted = hex.substr(1);
  • red = parseInt(splitted.slice(0, 2), 16) / 255;
  • ...splitted.slice(2, 4)...
  • ...splitted.slice(4, 6)...
Genau! Now we're ready to build our function:








2 - From CG color to HTML color:

And now, let's invert the process!
Our function will take as input an array on float numbers, ranged between 0 and 1, and will return a string.
The Javascript function to translate a number to a string value is this:
By the way, we'll have an array and we need to multiply the value for 255:
Next step: checking if the value is less or more than 'F'. Why? Because we need to build a string.length = 6 plus the '#' character elsewhere we'll not perform a correct conversion.
  • if (r.length == 1) { r = '0' + r };
As last step, let's compose the final string:
  • hex = '#' + r + g + b;
We're ready to build our new function:




As I've written before, I'm not handling alpha channel because I don't need it but you can do that in few minutes if you want.

Greetings from Berlin and Campus Party Europe!
Pietro

No comments:

Post a Comment