How to Convert TColor to a Hex String and Vice Versa
Delphi uses TColor to represent colors but HTML requires a string name (139 colors have names in the web palette) or a hex number. Here’s the code to convert a TColor color value to hex a string and vise versa.
The functions use the Windows API GetRValue(), GetBValue(), GetGValue() and RGB() functions.
!Note: If your are going to use this in a unit that has a form remember that the colColor and sColor parameters must have different names than Color else the function will take the form’s color.
(* Returns a string representation of the colColor parameter in XXXXXX format,
** X being a hex digit.
*)
function TColorToHex(const colColor: TColor): string;
begin
Result := IntToHex(GetRValue(colColor), 2) + { Red value }
IntToHex(GetGValue(colColor), 2) + { Green value }
IntToHex(GetBValue(colColor), 2); { Blue value }
end;
{ sColor should be in XXXXXX format, X being a hex digit }
function HexToTColor(const sColor: string): Cardinal;
begin
Result := RGB(StrToInt('$' + Copy(sColor, 1, 2)), { Get red value }
StrToInt('$' + Copy(sColor, 3, 2), { Get green value }
StrToInt('$' + Copy(sColor, 5, 2)); { Get blue value }
end;