Search code examples
delphidelphi-xeimagelist

Convert png/jpg/gif to ico


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


Solution

  • 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;