Convert RGB to HEX

Turn RGB channels or a CSS rgb() value into hexadecimal output.

Use Color::rgb() for normalized channels, or parse a CSS rgb() string when your values are bytes:

use PhpColor\Color\Color;

echo Color::rgb(59 / 255, 130 / 255, 246 / 255)->toHex();
// #3b82f6

echo Color::parse('rgb(59 130 246)')->toHex();
// #3b82f6
use PhpColor\Color\Color; echo Color::rgb(59 / 255, 130 / 255, 246 / 255)->toHex(); // #3b82f6 echo Color::parse('rgb(59 130 246)')->toHex(); // #3b82f6

Include alpha when you need eight-digit #rrggbbaa output:

echo Color::parse('rgb(59 130 246 / 80%)')->toHex(true);
// #3b82f6cc
echo Color::parse('rgb(59 130 246 / 80%)')->toHex(true); // #3b82f6cc

Hexadecimal is an sRGB byte format. Converting a wide-gamut value to hex clamps and quantizes it. See Generate hexadecimal output for that boundary.