Message Boards Message Boards

Hex colors in Mathematica

A certain project I was working on a few months ago required hex color codes to be parsed in Mathematica. There isn't a built-in function for this, but a quick Wikipedia search indicated that they're actually quite simple. The hex code for any given RGB color is just the concatenation of the hex forms of the red, green, and blue color values.

From Wikipedia:

For example, consider the color where the red/green/blue values are decimal numbers: red=36, green=104, blue=160 (a greyish-blue color). The decimal numbers 36, 104 and 160 are equivalent to the hexadecimal numbers 24, 68 and A0 respectively. The hex triplet is obtained by concatenating the 6 hexadecimal digits together, 2468A0 in this example.

The reverse, converting hex to RGB, is also quite simple. Here's the function I wrote:

hexToRGB[hex_]:=RGBColor @@ (N[FromDigits[StringJoin[#], 12]/255] & /@ 
   Partition[Characters[hex], 2])

There are a few nuances this doesn't cover, (like the shorthand three-character form) but they're all easily implemented.

I would strongly recommend that Wolfram incorporate hex color conversion in the next release of Mathematica.

POSTED BY: Jesse Friedman
2 Replies

There is a build-in function for this: https://reference.wolfram.com/language/ref/RGBColor.html

POSTED BY: Piotr Wendykier

Oops, I didn't see that. Thanks!

POSTED BY: Jesse Friedman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract