Function Repository Resource:

HexToColor

Source Notebook

Convert hex strings into colors

Contributed by: Michael Sollami

ResourceFunction["HexToColor"][hex]

converts a string hex into an equivalent color.

ResourceFunction["HexToColor"][hex,form]

converts a string hex into a color specified by form.

Details and Options

The first argument hex should be a string of the format "#XXXXXX" (where each X is a digit or a letter in the range of "a" to "f").
The first argument hex may also be given in the following formats:
"#RRGGBBAA"eight-digit hexadecimal
"#RRGGBB"six-digit hexadecimal
"#RGB"three-digit hexadecimal form
"#RRGG"no blue channel
"#RR"only red channel
In the single argument case, the form defaults to "RGB" and an RGBColor[] is returned.
Allowed values for form include:
"RGB" | "RGBA"RGBColor value with optional alpha
"Real"List of real channel values in the interval [0,1]
"Integer"List of integer channel values in the set {0,,255}
ResourceFunction["HexToColor"] ignores capitalization and works on strings with or without a prefixed octothorpe.
ResourceFunction["HexToColor"] is Listable.

Examples

Basic Examples (5) 

Convert hex strings into colors:

In[1]:=
ResourceFunction[
 "HexToColor"] /@ {"#f", "#0f0", "#8080", "#a03393", "#a0339333"}
Out[1]=

Convert hex strings with alpha:

In[2]:=
ResourceFunction["HexToColor"]["#22ffff44", #] & /@ {"RGBA", "Real"}
Out[2]=

Convert hex strings directly to integer lists:

In[3]:=
# -> ResourceFunction["HexToColor"][ResourceFunction["ColorToHex"]@#, "Integer"] & /@ RandomColor[10] // Multicolumn
Out[3]=

Create a basic RGB color table:

In[4]:=
Dataset[{#, ResourceFunction["HexToColor"][#, "RGB"], ResourceFunction["HexToColor"][#, "Integer"]} & /@ {"#000000", "#C0C0C0", "#FFFFFF", "#FF0000", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#FF00FF"}]
Out[4]=

HexToColor is effectively the inverse of the resource function ColorToHex:

In[5]:=
Row@{ColorSlider[Dynamic[c]], Spacer[10], Framed@Dynamic[
    Style[h = ResourceFunction["ColorToHex"]@c, FontFamily -> "Courier", FontSize -> 30, FontColor -> ResourceFunction["HexToColor"]@h]]}
Out[5]=

Properties and Relations (2) 

The system symbol RGBColor works for some cases out of the box:

In[6]:=
tests = {"#00ff00", "#00f", "#ff000", "#00", "#ffff", "0ff", "#ff000099"};
In[7]:=
RGBColor /@ tests
Out[7]=

However, HexToColor offers many additional conveniences, as well as support for alpha:

In[8]:=
ResourceFunction["HexToColor"]@tests
Out[8]=

Publisher

Michael Sollami

Version History

  • 1.0.0 – 11 December 2020

Related Resources

License Information