Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract frames from a TGifImage into Bitmaps?

Tags:

gif

delphi

The demo below tries to draw the GIF on form's canvas. It doesn't work. The image won't advance. How to make it work?

procedure TForm1.FormCreate(Sender: TObject);
begin
 GIF := TGIFImage.Create;
 GIF.LoadFromFile('c:\2.gif');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
 GIF.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
VAR i: Integer;
begin
 REPEAT
  for i:= 0 to GIF.Images.Count-1 DO
   begin
    DisplayGifFrame(i);
    Sleep(30);
   end;
 UNTIL FALSE;
end;


procedure TForm1.DisplayGifFrame(AIndex: Integer);
VAR
   Renderer: TGIFRenderer;
begin
 Renderer := TGIFRenderer.Create(GIF);
 TRY
  Renderer.Animate := TRUE;
  Renderer.FrameIndex := AIndex;
  Renderer.Draw(Canvas, Canvas.ClipRect); 

  {save frame in a bitmap here. save bitmap to disk}
  // xxx 
 FINALLY
  Renderer.Free;
 end;
end;

What I want to achieve:
I want to extract all frames from a GIF and put each frame IN A UNIQUE bitmap.


Update:
Continued here: Cannot draw GIF on dynamically created TBitmap(s)

like image 222
Server Overflow Avatar asked Feb 28 '13 13:02

Server Overflow


1 Answers

Try this:

procedure TForm1.Button1Click(Sender: TObject);
var
  GIF: TGIFImage;
  Bitmap: TBitmap;
  I: Integer;
  GR: TGIFRenderer;
  R: TRect;
begin
  GIF := TGIFImage.Create;      
  Bitmap := TBitmap.Create;
  try
    GIF.LoadFromFile('c:\test\test.gif');
    Bitmap.SetSize(GIF.Width, GIF.Height);
    GR := TGIFRenderer.Create(GIF);
    try
      for I := 0 to GIF.Images.Count - 1 do
      begin
        if GIF.Images[I].Empty then Break;
        GR.Draw(Bitmap.Canvas, Bitmap.Canvas.ClipRect);
        GR.NextFrame;
        Bitmap.SaveToFile(Format('%.2d.bmp', [I]));
      end;
    finally
      GR.Free;
    end;  
  finally
    GIF.Free;
    Bitmap.Free;
  end;
end;

The above code takes into account Frame's Disposal method. see related question here.

like image 182
kobik Avatar answered Oct 30 '22 09:10

kobik