Board index » delphi » TBitmap and TImage : basic q. about memory management

TBitmap and TImage : basic q. about memory management


2004-01-20 09:31:12 AM
delphi278
A simple doubt about memory management when assigning a TBitmap
to a TImage component:
Say a have a Image1:TImage component in a form, and the image
must be updated at runtime; say, when a button is pressed.
I coded the method, which responds to the event by reading the filename,
loading
it in a TBitmap and assigning it to the TImage object in this way:
ImgFilename := (... get from another control...)
Bitmap1 := TBitmap.Create;
Bitmap1.LoadFromFile(ImgFilename);
Image1.Picture.Assign(Bitmap1);
Bitmap1.Free;
This seems to work.
The question is : is this correct , in what respect to memory management ?
Could this introduce a memory leak? (if it is executed many times,
with different images)
How does the Assign method work ? It copies the TBitmap object to the
Picture's own memory space ?
That is: before invoking Bitmap1.Free (which MUST be invoked to avoid a
memory
leak, if I am not mistaken) immediately after the Picture.Assign , are there
two
distinct regions in memory that hold (in different formats, perhaps) the
bitmap,
one in the TBitmap object, the other in the TImage.Picture component ?
Is this so ?
Thanks
Hernan
 
 

Re:TBitmap and TImage : basic q. about memory management

"Hernan Gonzalez" <XXXX@XXXXX.COM>writes:
Quote
Image1.Picture.Assign(Bitmap1);
Bitmap1.Free;
The question is : is this correct , in what respect to memory management ?
Yes.
Quote
Could this introduce a memory leak? (if it is executed many times,
with different images)
Only if there were to be some failure in the code. You could do some
resoure protection like this:
Bitmap1 := TBitmap.Create;
try
Bitmap1.LoadFromFile(ImgFilename);
Image1.Picture.Assign(Bitmap1);
finally
Bitmap1.Free;
end;
Quote
How does the Assign method work ? It copies the TBitmap object to the
Picture's own memory space ?
Sort of. It actually bumps the reference count to the info and saves a
pointer to it.
Quote
That is: before invoking Bitmap1.Free (which MUST be invoked to avoid a
memory
leak, if I am not mistaken)
Yes.
Quote
are there
two
distinct regions in memory that hold (in different formats, perhaps) the
bitmap,
one in the TBitmap object, the other in the TImage.Picture component ?
Is this so ?
No. As I mentioned above, there's a reference count on the info. All
that happens is that the reference count gets incremented when you do
the assign and decremented when you do the Free. Since the count is
still non-zero, the image information is not discarded at that time.
Just for simplification purposes, you could have done:
ImgFilename := (... get from another control...)
Image1.Picture.Bitmap.LoadFromFile(ImgFilename);
Good luck.
Kurt