When I load a new image in a TBitmap I must destroy the existing one first?

852 views Asked by At

I am loading multiple images from resources in a TImageList at runtime with this code:

 Bitmap:=TBitmap.Create;
 MyIcons:=TImageList.Create(self);
 Bitmap.LoadFromResourceName(HInstance,'DEFAULT16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.LoadFromResourceName(HInstance,'FOLDER16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.LoadFromResourceName(HInstance,'BACK16');
 MyIcons.AddMasked(BitMap,clRed);
 Bitmap.Free;

I want to know if I should destroy the previous bitmap (Bitmap.Assign(nil)) when I load a new one or this is done automatically in LoadFromResourceName method. I mean I don't want to have memory leakage...

1

There are 1 answers

0
David Heffernan On BEST ANSWER

No. When LoadFromResourceName executes, it clears any memory and resources used by the previous image, and loads the new one.

Your code is fine, modulo the missing try/finally. It should be:

Bitmap := TBitmap.Create;
try
  ....
finally
  Bitmap.Free;
end;

Without that, should an exception be raised in between assigning to Bitmap, and destroying the object, the object would not be destroyed and would be leaked.