8

I have read here http://delphi.about.com/od/adptips2005/qt/cleartimage.htm that a way to clear an image from a TImage is to assign nil to .Picture, like this:

Image1.Picture := nil;

I just want to be sure... I guess the Image1.Picture.loadFromFile(fileName) will allocate some memory and simply setting it to nil, without freeing the memory, will lead to a memory leak.

Am I correct? If this is so, which is the "proper" way to unload and clear an image from a TImage?

ZioBit
  • 905
  • 10
  • 29
  • 6
    take a look at `procedure TPicture.SetGraphic(Value: TGraphic);` in Graphics, you will find that the exisitng graphic will be freed. – bummi Jun 02 '14 at 10:03
  • 3
    I didn't know I had access to the whole source code for the VCL... Wow, you helped me discover a whole new world ;) Next time I will dig into it before posting a question. Thank you! – ZioBit Jun 02 '14 at 10:31
  • @bummi You should post this as an answer. – J... Jun 02 '14 at 16:13
  • I just discovered that Image1.Picture.loadFromFile('') will clear the image. Cool. right? – Gabriel Oct 23 '17 at 19:46

1 Answers1

14

The TImage.Picture setter is TImage.SetPicture() in the ExtCtrls unit, which calls TPicture.Assign() in the Graphics unit, which calls TPicture.SetGraphic(), which will free an existing Graphic before assigning a new Graphic.

So the usage of

Image1.Picture := nil; 

Will ultimately call

Image1.Picture.SetGraphic(nil); 

And will not cause any memory leak.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
bummi
  • 27,123
  • 14
  • 62
  • 101