Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve the first frame from a large GIF (in optimal time)

I need to obtain the first frame from an animated GIF file. This is easy to achieve by loading the file in a TGIFImage object:

  GIF.LoadFromFile(FileName)
  BMP.Assign(GIF)

The problem is that for (large) animated GIF files this takes a while... my computer needs 12 seconds and a LOT of RAM to load a 50MB file.

I was hoping that I will be able to pass the file to TCustomGIFRenderer and extract the first frame. But TCustomGIFRenderer only operates on 'live' (in memory) GIF images.

Is it possible to get only the first frame without loading the whole file?

like image 500
Server Overflow Avatar asked Dec 07 '25 08:12

Server Overflow


1 Answers

Have you tried GDI+.

uses GDIPAPI, GDIPOBJ, GDIPUTIL;

procedure TForm1.Button1Click(Sender: TObject);
var
  GPImage: TGPImage;
  GPGraphics: TGPGraphics;
  Bitmap: TBitmap; // first frame
begin
  GPImage := TGPImage.Create('D:\animated-tiger.gif');
  try
    Bitmap := TBitmap.Create;
    try
      Bitmap.Width := GPImage.GetWidth;
      Bitmap.Height := GPImage.GetHeight;
      GPGraphics := TGPGraphics.Create(Bitmap.Canvas.Handle);
      try
        GPGraphics.DrawImage(GPImage, 0, 0, Bitmap.Width, Bitmap.Height);
        Image1.Picture.Assign(Bitmap);
      finally
        GPGraphics.Free;;
      end;
    finally
      Bitmap.Free;
    end;
  finally
    GPImage.Free;
  end;
end;

You might also want to try TWICImage (for newer Delphi version). For older Delphi version which do not have TWICImage build-in, see this Q: Delphi 2007 using Windows Imaging Component (WIC).

In both cases (GDI+/WIC) only the first GIF frame will be extracted.

like image 173
kobik Avatar answered Dec 10 '25 03:12

kobik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!