5

I have multiple images some of them are png some of them jpg and gif and i want to display them in a listview as thumbails TImageList supports only icons how can i convert them to be able to insert them in TImageList.

I am using Delphi XE

opc0de
  • 11,557
  • 14
  • 94
  • 187

1 Answers1

9

To specifically answer the question, also to take simple resizing into account (for thumbnails), some example code:

var
  Img: TImage;
  BmImg: TBitmap;
  Bmp: TBitmap;
  BmpMask: TBitmap;
  IconInfo: TIconInfo;
  Ico: TIcon;
begin
  Img := TImage.Create(nil);
  Img.Picture.LoadFromFile(...

  BmImg := TBitmap.Create;
  BmImg.Assign(Img.Picture.Graphic);
  Img.Free;

  Bmp := TBitmap.Create;
  Bmp.SetSize(ImageList1.Width, ImageList1.Height);
  SetStretchBltMode(Bmp.Canvas.Handle, HALFTONE);
  StretchBlt(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height,
              BmImg.Canvas.Handle, 0, 0, BmImg.Width, BmImg.Height, SRCCOPY);
  BmImg.Free;

  BmpMask := TBitmap.Create;
  BmpMask.Canvas.Brush.Color := clBlack;
  BmpMask.SetSize(Bmp.Width, Bmp.Height);

  FillChar(IconInfo, SizeOf(IconInfo), 0);
  IconInfo.fIcon := True;
  IconInfo.hbmMask := BmpMask.Handle;
  IconInfo.hbmColor := Bmp.Handle;

  Ico := TIcon.Create;
  Ico.Handle := CreateIconIndirect(IconInfo);

  ImageList1.AddIcon(Ico);

  Bmp.Free;
  BmpMask.Free;
  Ico.Free;  // calls DestroyIcon
end;

or, without creating an icon:

var
  Img: TImage;
  BmImg: TBitmap;
  Bmp: TBitmap;
begin
  Img := TImage.Create(nil);
  Img.Picture.LoadFromFile(..

  BmImg := TBitmap.Create;
  BmImg.Assign(Img.Picture.Graphic);
  Img.Free;

  Bmp := TBitmap.Create;
  Bmp.SetSize(ImageList1.Width, ImageList1.Height);
  SetStretchBltMode(Bmp.Canvas.Handle, HALFTONE);
  StretchBlt(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height,
              BmImg.Canvas.Handle, 0, 0, BmImg.Width, BmImg.Height, SRCCOPY);
  BmImg.Free;

  ImageList1.AddMasked(Bmp, clNone);

  Bmp.Free;
end;
Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • I often get the exception : Out of system resources why do you think is that ? – opc0de Dec 23 '11 at 13:37
  • @opc0de, the above samples work with a few gdi handles, but as far as I can see there should be no leak. But you would of course want to modify the code to guarantee freeing vcl objects, using try finally blocks. I can't really say.. – Sertac Akyuz Dec 23 '11 at 13:44
  • I used a jpeg image to dump the thumbnail on disk after i replaced the jpeg with a bmp i stopped getting that nasty error. There wasn't no leak but i don't know... – opc0de Dec 23 '11 at 19:38