Jump to content
isola

TImage inside TComponent serializaton

Recommended Posts

I have a class that is inherited from TComponent.
The class have some published fields.

It is possible in runtime using the bundle below save the class to a file.

MemStream.WriteComponent(self);
FileStream := TFileStream.Create(FStorageName, fmCreate);
ObjectBinaryToText(MemStream, FileStream);

Then it's possible using below code to read saved data back into an object directly.

ObjectTextToBinary(FileStream, MemStream);

 

 

Everything works well for simple types(Int, string, boolean).
This serialization works as well for some other types (TStringList, TCollection).

What about TImage class?
It seems published TImage is ignored.
But TImage is also the descendant of TComponent. 

Does Delphi use the same approach to save TForm to dfm-files?
Whether any extra effort should be made to serialize TImage?

Share this post


Link to post

Make the Owner of that TImage instance your component and set csSubComponent in the TImages ComponentStyle.

 

That means, the image should be created like this:

FImage := TImage.Create(Self);
FImage.SetSubComponent(True);

 

  • Like 2

Share this post


Link to post
1 hour ago, isola said:

Does Delphi use the same approach to save TForm to dfm-files

or more simple way;

  • you can use only "Memory streams instead save on file"
procedure TForm1.Button1Click(Sender: TObject);
var
  LMemStream: TMemoryStream;
  LStrStream: TStringStream;
begin
  LMemStream := TMemoryStream.Create;
  try
    LMemStream.WriteComponent(Image1);
    LMemStream.SaveToFile('myTImage.bin');
    //
    LStrStream := TStringStream.Create;
    try
      LMemStream.Position := 0;
      ObjectBinaryToText(LMemStream, LStrStream);
      LStrStream.Position := 0;
      Memo1.Text          := LStrStream.DataString;  // showing the propers
    finally
      LStrStream.Free;
    end;
    //
    Image1.Picture.Bitmap := nil; // just for test...
  finally
    LMemStream.Free;
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  LMemStream: TMemoryStream;
begin
  LMemStream := TMemoryStream.Create;
  try
    LMemStream.LoadFromFile('myTImage.bin');
    LMemStream.ReadComponent(Image1);
  finally
    LMemStream.Free;
  end;
end;

image.png.d549c14a5761e208632eaa5c634d5c5b.png

 

Edited by programmerdelphi2k
  • Haha 2

Share this post


Link to post
FImage := TImage.Create(Self);
FImage.SetSubComponent(True);

It works.
Uwe Raabe, thank you very much!

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×