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:

function ColorToHtml(const Color: Integer): AnsiString;
const
  Hex = '0123456789ABCDEF';
var
  b, s: Byte;
begin
  Result := '#';
  s := 0;
  repeat
    b := (Color shr s) and $FF;
    Result := Result + Hex[b div 16 + 1] + Hex[b mod 16 + 1];
    Inc(s, 8);
  until s = 24;
end;

function HtmlToColor(const Html: AnsiString): Integer;
const
  Hex = '0123456789ABCDEF';
var
  p, s: Byte;
begin
  Result := 0;
  s := 0;
  p := 1;
  if Html[1] = '#' then
    Inc(p);
  repeat
    Result := Result or (((Pos(Html[p], Hex) - 1) * 16 +
      Pos(Html[p + 1], Hex) - 1) shl s);
    Inc(p, 2);
    Inc(s, 8);
  until s = 24;
end;

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:

procedure ColorToRGB(const Color: Integer; out R, G, B: Byte);
begin
  R := Color and $FF;
  G := (Color shr 8) and $FF;
  B := (Color shr 16) and $FF;
end;

function RGBToColor(const R, G, B: Byte): Integer;
begin
  Result := R or (G shl 8) or (B shl 16);
end;

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

Read More