Delphi: Converting color values to HTML colors

Delphi uses a decimal representation for colors, the way these are built up is simply like integer values which means that in the memory the colors are stored not as RGB, but BGR. If we want to convert these color values to HTML hex colors, we need to take these into account as those are represented as RGB. Here are some methods to perform the conversion:

01function ColorToHtml(const Color: Integer): AnsiString;
02const
03  Hex = '0123456789ABCDEF';
04var
05  b, s: Byte;
06begin
07  Result := '#';
08  s := 0;
09  repeat
10    b := (Color shr s) and $FF;
11    Result := Result + Hex[b div 16 + 1] + Hex[b mod 16 + 1];
12    Inc(s, 8);
13  until s = 24;
14end;
15 
16function HtmlToColor(const Html: AnsiString): Integer;
17const
18  Hex = '0123456789ABCDEF';
19var
20  p, s: Byte;
21begin
22  Result := 0;
23  s := 0;
24  p := 1;
25  if Html[1] = '#' then
26    Inc(p);
27  repeat
28    Result := Result or (((Pos(Html[p], Hex) - 1) * 16 +
29      Pos(Html[p + 1], Hex) - 1) shl s);
30    Inc(p, 2);
31    Inc(s, 8);
32  until s = 24;
33end;

Read More

Delphi: Decimal color to RGB and back

Converting a decimal color value (24-bit) to RGB in Delphi is easy using bitshifts, the reverse is true as well. Here’s how it’s done:

01procedure ColorToRGB(const Color: Integer; out R, G, B: Byte);
02begin
03  R := Color and $FF;
04  G := (Color shr 8) and $FF;
05  B := (Color shr 16) and $FF;
06end;
07 
08function RGBToColor(const R, G, B: Byte): Integer;
09begin
10  Result := R or (G shl 8) or (B shl 16);
11end;

Take in mind that Delphi TColor is a 24-bit integer decimal color representation.

Read More