Mirror

How to convert a bitmap or icon to Hex code (Views: 101)


Problem/Question/Abstract:

If you load an image into a Delphi component at design time, then view the form as Text, you can see the hex code that makes up the image. I assume this is how Windows/ Delphi stores the image. How can I get the data in the same format, at runtime, as a string, to save to a text file?

Answer:

function StreamToHexStr(Stream: TStream; LineSize: Integer = 80): TStringList;
var
  Value: Byte;
begin
  Result := TStringList.Create;
  if Result.Count = 0 then
    Result.Add('');
  repeat
    Stream.Read(Value, 1);
    Result[Result.Count - 1] := Result[Result.Count - 1] + IntToHex(Value, 2);
    if Length(Result[Result.Count - 1]) >= LineSize then
      Result.Add('');
    Stream.Seek(1, soFromCurrent);
  until
    Stream.Position >= Stream.Size - 1;
  if Result[Result.Count - 1] = '' then
    Result.Delete(Result.Count - 1);
end;

<< Back to main page