2008. szeptember 7., vasárnap

Converting a group of images from a TImageList into one single bitmap


Problem/Question/Abstract:

I have a program that adds images to a TImageList at runtime. What I would like to do is save the images to a file so that it another program can load in the images to its TImageList.

Answer:

The best way to load a TImageList from a resource is to pack all images into one bitmap and load them all in one go. For this you need the bitmap, of course.

So, create a new project, drop a TImageList on the form and add the icons to it at design-time, as usual. Add a handler for the forms OnCreate event and do it like in the little program ImageListConverter below.

The result is a 'strip' bitmap with all images in the list, here saved as 'c:\temp\images.bmp'.

Open this bitmap in MSPaint and save it again under the same name as a 256 or 16 color bitmap, it will usually have a higher color depth since the VCL creates bitmaps with the color depth of your current video mode by default. The 'transparent' color for this bitmap is clOlive, since that is what we filled the bitmap with before painting the images on it transparently.

The next step is to add this bitmap to a resource file and add the resource to your project. You can do that with the image editor as usual or create a RC file and add it to your project group (requires D5). The RC file would contain a line like

IMAGES1 BITMAP c:\temp\images.bmp

You can now load this resource into your projects imagelist with

ImageList2.ResInstLoad(HInstance, rtBitmap, 'IMAGES1', clOlive);

Note that the width and height setting of the imagelist has to be the same as the one you saved the images from, otherwise the bitmap will not be partitioned correctly.


program ImageListConverter;

procedure ImageList2Bitmap(anImageList: TImageList; const sBMPFile: string);
var
  Bmp: TBitmap;
  i: Integer;
begin
  Bmp := TBitmap.Create;

  try
    Bmp.Width := anImageList.Width * ImageList1.Count;
    Bmp.Height := anImageList.Height;

    with Bmp.Canvas do
    begin
      Brush.Color := clOlive;
      Brush.Style := bsSolid;
      FillRect(ClipRect);
    end;
    for i := 0 to anImageList.Count - 1 do
      anImageList.Draw(Bmp.Canvas, i * anImageList.Width, 0, i);
    Bmp.SaveToFile(sBMPFile);
  finally
    Bmp.Free
  end;
end;

begin
  ImageList2Bitmap(myImageList1, 'c:\temp\images.bmp');
end.

Nincsenek megjegyzések:

Megjegyzés küldése