Convert Hex Colors to ANSI Escape Codes
Convert CSS hex color values like #FF5733 to ANSI escape sequences for terminal output. Covers true color (24-bit) and nearest 256-color approximation methods.
Detailed Explanation
Converting Hex Colors to ANSI
Web developers frequently need to replicate hex colors in terminal output. This guide covers converting hex colors to both true color (24-bit) and 256-color ANSI escape sequences.
Hex to True Color
The conversion is straightforward — parse the hex into RGB components:
def hex_to_ansi_truecolor(hex_color, is_bg=False):
hex_color = hex_color.lstrip('#')
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
prefix = 48 if is_bg else 38
return f"\033[{prefix};2;{r};{g};{b}m"
Hex to Nearest 256-Color
For terminals that do not support true color:
def hex_to_ansi256(hex_color):
hex_color = hex_color.lstrip('#')
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
# Check grayscale
if r == g == b:
if r < 4: return 16
if r > 248: return 231
return round((r - 8) / 10) + 232
# Map to 6x6x6 cube
values = [0, 95, 135, 175, 215, 255]
ri = min(range(6), key=lambda i: abs(values[i] - r))
gi = min(range(6), key=lambda i: abs(values[i] - g))
bi = min(range(6), key=lambda i: abs(values[i] - b))
return 16 + (36 * ri) + (6 * gi) + bi
Popular Hex Colors and Their ANSI Equivalents
| Hex | Name | True Color Code | Nearest 256 |
|---|---|---|---|
#FF5733 |
Burnt Orange | 38;2;255;87;51 |
202 |
#3498DB |
Dodger Blue | 38;2;52;152;219 |
68 |
#2ECC71 |
Emerald | 38;2;46;204;113 |
42 |
#E74C3C |
Alizarin | 38;2;231;76;60 |
196 |
#9B59B6 |
Amethyst | 38;2;155;89;182 |
133 |
#1ABC9C |
Turquoise | 38;2;26;188;156 |
36 |
Node.js Implementation
function hexToAnsi(hex, isBg = false) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
const prefix = isBg ? 48 : 38;
return `\x1b[${prefix};2;${r};${g};${b}m`;
}
// Usage
const red = hexToAnsi('#FF5733');
console.log(`${red}Hello World\x1b[0m`);
This makes it easy to use your application's brand colors consistently in both web and terminal contexts.
Use Case
Converting hex to ANSI is essential when building CLI tools that match a company's brand colors, creating terminal themes from web color palettes, or implementing design systems that span both web and terminal interfaces. Tools like Tailwind CSS color palettes can be directly translated to terminal colors for consistent developer experiences.