Convert CIE XYZ back to sRGB
This is the inverse of the RGB-to-XYZ transform: it takes device-independent CIE XYZ tristimulus values and turns them back into displayable sRGB and hex. It is the final step when you have worked in a perceptual space such as Lab or have measured a color with a colorimeter and need a value you can actually paint to screen. A built-in gamut check flags colors that sRGB cannot reproduce.
How it works
The X, Y, Z inputs are divided by 100 to put them on a 0–1 scale, then multiplied by the inverse sRGB matrix for the D65 white point:
R = 3.2404542*X - 1.5371385*Y - 0.4985314*Z
G = -0.9692660*X + 1.8760108*Y + 0.0415560*Z
B = 0.0556434*X - 0.2040259*Y + 1.0572252*Z
Those linear values are gamma-encoded with the sRGB transfer function — 1.055 * c^(1/2.4) - 0.055 above 0.0031308, otherwise c * 12.92 — and scaled to 0–255. If any linear channel lands below 0 or above 1, the color sits outside the sRGB gamut and is clamped.
Example and notes
The D65 white point X = 95.05, Y = 100.00, Z = 108.88 converts cleanly to #ffffff. Deep, saturated spectral colors — many cyans and greens especially — frequently fall outside sRGB and will trigger the out-of-gamut warning; the clamped value is the closest representable color, not an exact match. Always verify your XYZ values share the D65 white point and the Y = 100 scale, since both assumptions are baked into the matrix.