Function Repository Resource:

ColorToHex

Source Notebook

Convert a color to a hex string

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["ColorToHex"][color]

converts color into an equivalent hex string.

Details and Options

This will convert a color to an equivalent hex string in the format "#XXXXXX", where each X is either a digit character or a letter in the range of "a" to "f".
The value for color can be a color specification such as RGBColor[] or Red, or an explicit list of color channel values.
ResourceFunction["ColorToHex"][list] interprets list as follows:
{v}gray level
{v,α}gray level and α parameter
{r,g,b}red, green, blue levels
{r,g,b,α}RGB with α parameter

Examples

Basic Examples (6) 

Convert a color to a hex string:

In[1]:=
ResourceFunction["ColorToHex"][Red]
Out[1]=

Convert from RGB:

In[2]:=
ResourceFunction["ColorToHex"][RGBColor[0.368417, 0.506779, 0.709798]]
Out[2]=

Convert from HSB:

In[3]:=
ResourceFunction["ColorToHex"][Hue[0.5]]
Out[3]=

Give explicit RGB values:

In[4]:=
ResourceFunction["ColorToHex"][{1, 0.5, 0}]
Out[4]=

Apply to a list of colors:

In[5]:=
RandomColor[10]
Out[5]=
In[6]:=
ResourceFunction["ColorToHex"][%]
Out[6]=

Use a list of mixed color specifications:

In[7]:=
ResourceFunction[
 "ColorToHex"][{Red, {0, 1, 0}, CMYKColor[1, 1, 0, 0]}]
Out[7]=

Scope (1) 

The hex strings can be converted to RGB with RGBColor:

In[8]:=
color = RandomColor[]
Out[8]=
In[9]:=
RGBColor[ResourceFunction["ColorToHex"][color]]
Out[9]=

Applications (1) 

When creating HTML content, hex strings can be used as color specifications:

In[10]:=
html = StringTemplate["
<!DOCTYPE html>
<html><body><h2 style=\"color:`1`\">
Hex colors are useful for generating HTML content.
</h2></body></html>
"][ResourceFunction["ColorToHex"][Red]]
Out[10]=
In[11]:=
CloudExport[html, "HTML"]
Out[11]=
Out[11]=

Possible Issues (1) 

Pixel values are rounded to the nearest byte:

In[12]:=
color = RandomColor[]
Out[12]=
In[13]:=
newColor = RGBColor[ResourceFunction["ColorToHex"][color]]
Out[13]=
In[14]:=
ColorDistance[color, newColor]
Out[14]=

Version History

  • 2.0.0 – 19 September 2019
  • 1.0.0 – 15 August 2018

Related Resources

License Information