Wolfram Research

ColorToHex

Contributed by: Richard Hennigan (Wolfram Research)

Convert a color to a hex string

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".

Examples

Basic Examples

Use the function:

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

More Examples

Scope

Retrieve the ResourceFunction:

In[2]:=
ResourceFunction["ColorToHex"]
Out[2]=

Retrieve the ResourceObject:

In[3]:=
ResourceObject["ColorToHex"]
Out[3]=

Convert from RGB:

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

Convert from HSB:

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

Generalizations & Extensions

The hex strings can be converted to RGB with RGBColor:

In[6]:=
color = RandomColor[]
Out[6]=
In[7]:=
RGBColor[ResourceFunction["ColorToHex"][color]]
Out[7]=

Applications

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

In[8]:=
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[8]=
In[9]:=
CloudExport[html, "HTML"]
Out[9]=
Out[9]=

Possible Issues

Pixel values are rounded to the nearest byte:

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

Resource History