Should I use a TImageList , or another type of storage component for holding bitmaps?

By: Christopher Moeller

Abstract: Differences between TImageList and TList for TBitmaps.

What is the best way to store bitmap images in C++Builder?


Two easy ways stand out for storage of bitmap images in Builder.

The first method is to use the TImageList component, which specializes in holding a large number of same-sized images. The images in the list are contained in a single, wide bitmap in screen device format with an optional a monochrome bitmap for masking transparent parts of the bitmaps.  This component is dropped on a form and can have bitmaps added to it at design design-time or run-time.  It contains a number of methods to facilitate storing, retrieving, and drawing of the stored images.

If all of the images are going to be the same size, using the TImageList component may be be the most productive approach.  Typically, image lists are used to efficiently manage large sets of icons or bitmaps.

 For example:

  File  |  Close All
  File  |  New Application
  Drop a TImageList Component on the Form.
  Right-click on the component and choose ImageList Editor.
  Choose Add, browse to an Image, and then select and click OK.
  The image is now added to the TImageList.

A second way for storing bitmap images is to use a TList, which simply stores store pointers to your bitmaps .  This options is very useful if the stored bitmaps are different sizes.  Use of the TList for storing images entails dynamically creating the bitmaps, adding the bitmap pointer to the TList, recalling the bitmaps through the TList's Item property when needed, then finally deleting each bitmap in the list.  It is important to realize that the TList only stores pointers; it does not manage the memory consumed by each bitmap. You are responsible for deleting the bitmaps you store in the TList. 

The following is an example to help get started using the TList to store bitmaps:

// File | Close All
// File | New Application
// Drop a TImage and a Button on the Form

void __fastcall TForm1::Button1Click(TObject *Sender)
   TList* bmList = new TList;
   Graphics::TBitmap* bm = new Graphics::TBitmap;
   int index = 0;
      bm->Width = Image1->Width;     // Align the width to the TImage
      bm->Height = Image1->Height;   // Align the height to the TImage
      Image1->Picture->Graphic = bm; // Associate the bitmap
      index = bmList->Add(bm);      // Add the bitmap to the TList
      bm = NULL;                    // Clear the pointer just to show the list is working...
         // return the indexed pointer to the object in the list as a TBitmap*
      bm = (Graphics::TBitmap*)bmList->Items[index];
         // Free bitmap
      delete bm;
      bm = NULL;
         // clear the TList of all pointers stored in it.
         // Free List
      delete bmList;
      bmList = NULL;

Server Response from: ETNASC03