Color
Color Converter
Convert colors between HEX, RGB, and HSL formats. Includes alpha channel support.
Implementation
type RGB = { r: number; g: number; b: number; a?: number };
type HSL = { h: number; s: number; l: number; a?: number };
function hexToRgb(hex: string): RGB {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
if (!result) throw new Error('Invalid hex color');
return {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
a: result[4] ? parseInt(result[4], 16) / 255 : undefined,
};
}
function rgbToHex(rgb: RGB): string {
const toHex = (n: number) => n.toString(16).padStart(2, '0');
const alpha = rgb.a !== undefined ? toHex(Math.round(rgb.a * 255)) : '';
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}${alpha}`;
}
function rgbToHsl(rgb: RGB): HSL {
const r = rgb.r / 255;
const g = rgb.g / 255;
const b = rgb.b / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
if (max === min) return { h: 0, s: 0, l: Math.round(l * 100), a: rgb.a };
const d = max - min;
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
let h = 0;
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100), a: rgb.a };
}Usage
Use hexToRgb(), rgbToHex(), or rgbToHsl() to convert between formats.
Examples
Input:
Output:
hexToRgb("#ff5733")Output:
{ r: 255, g: 87, b: 51 }Input:
Output:
rgbToHex({ r: 255, g: 87, b: 51 })Output:
"#ff5733"