0
votes

The images iam loading are slightly different sizes. how can i get the smallest size and re-size them all to that size?

The code below is the loading of the images -> converting to bmp -> adding to imagelist

after about 3 images it gives error invalid image size. due to image size too big for the size i gave imagelist at start.

procedure TForm1.LoadImages(const Dir: string);
var
  z,i: Integer;
  CurFileName: string;
  JpgIn: TJPEGImage;
  BmpOut: TBitmap;
begin
  i := 0;
  z := 1;
  while True do
  begin
    CurFileName := Format('%s%d.jpg',
                          [IncludeTrailingPathDelimiter(Dir), i]);
    if not FileExists(CurFileName) then
      Break;
    JpgIn := TJPEGImage.Create;
    try
      JpgIn.LoadFromFile(CurFileName);
      if z = 1 then
       begin
        ImageList1.SetSize(jpgin.width, jpgin.Height);
        z := 0;
       end;
      BmpOut := TBitmap.Create;
      try
         BmpOut.Assign(JpgIn);
         ImageList1.Add(BmpOut, nil);
      finally
        BmpOut.Free;
      end;
    finally
      JpgIn.Free;
    end;
    Inc(i);
  end;
  if ImageList1.Count > 0 then
  begin
    BmpOut := TBitmap.Create;
    try
      ImageList1.GetBitmap(1, BmpOut);
      zimage1.Bitmap.Assign(bmpout);
      zimage1.Repaint;
    finally
      BmpOut.Free;
    end;
  end;
end;
1
I have seen were You can set the TImageList to the maximum size encountered, and then set the pixels that are outside of the aspect ratio of individual images to the transparent background color. but for this i would still need to know the maximum size encounterd. Which each time it will be differentGlen Morse
You could have just linked to the previous question for the code being used, for future reference, and asked the follow-up question here. Remy gave an idea for a solution; I'll explain the problem. If you change the size of an imagelist once you've started adding images, the imagelist is cleared, so you can't change the size. Adding images of a different size therefore raises an exception, because the image list is internally implemented as a single wide image (the width of the first image multiplied by the image count). Obviouly, then, this fails with an off-sized image.Ken White

1 Answers

2
votes

Once you start putting images into the TImageList, you cannot resize it, and all images must be the same size. So you will have to pre-load all of the images ahead of time so you can then determine the smallest size available, THEN crop/stretch any larger images to the smaller size, THEN you can load the final images into the TImageList.

Have your loop store all of the TJPEGImage into a TList or TObjectList and not free them right away, then you can loop through that list calculating the smallest size, then loop through the list again resizing the images as needed, then loop through the list again adding the images to the TImageList, and then finally loop through the list freeing the images.