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;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.