Wolfram Research

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

Examples

Basic Examples

Use the function:

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

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]=
Out[8]=
Out[8]=

Possible Issues

Pixel values are rounded to the nearest byte:

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information