如何从TGifImage中提取帧到位图?

时间:2013-02-28 13:39:42

标签: delphi gif

下面的演示试图在表单的画布上绘制GIF。它不起作用。图像不会前进。如何使它工作?

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;

我想要实现的目标:
我想从GIF中提取所有帧并将每个帧放入一个UNIQUE位图。


更新
接下来是:Cannot draw GIF on dynamically created TBitmap(s)

1 个答案:

答案 0 :(得分:8)

试试这个:

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;

以上代码考虑了Frame的Disposal方法。请参阅相关问题here