Search code examples
delphifiremonkeydelphi-10.3-rio

How to save Viewport3D as Image File?


I'm developing a Firemonkey (FMX) application using Delphi 10.3.3.

I have a Viewport3D component. Inside the Viewport3D, i have many 3D Shapes such as TCube and TRectangle3D.

I need to save the contents of the Viewport3D (a screenshot of the current view) to an image file. I prefer to save as a transparent PNG. How can I do that?


Solution

  • Image1.Bitmap.Assign( Viewport3D1.MakeScreenshot );
    

    for converting bitmap to png;

    Uses FMX.Surfaces;
    
    procedure TMain.Button1Click(Sender: TObject);
    var
     Stream: TMemoryStream;
     Surf: TBitmapSurface;
    
    begin
     Stream:=TMemoryStream.Create;
     Stream.Position := 0;
     Surf := TBitmapSurface.Create;
     try
      Surf.Assign(Viewport3D1.MakeScreenshot);
      if TBitmapCodecManager.SaveToStream(Stream, Surf, '.png') then
      Begin
       Stream.SaveToFile('screenshot.png');
      End
      Else
       raise EBitmapSavingFailed.Create('Error saving Bitmap to png');
     finally
      Stream.Free;
      Surf.Free;
     end;
    end;