Saving Current Frame into an Image File XNA 4.0

This implementation will save current frame into an image file named “anImageFile.png”

Put this code into your draw method.

if (takeScreenshot)
{
   Color[] colors = new Color[GraphicsDevice.Viewport.Width * GraphicsDevice.Viewport.Height];
   GraphicsDevice.GetBackBufferData<Color>(colors);

   Texture2D tex2D = new Texture2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
   tex2D.SetData<Color>(colors);

   String filename = "anImageFile.png";

   FileStream stream = File.Create(filename);

   tex2D.SaveAsPng(stream, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

   stream.Flush();
   stream.Close();

   takeScreenshot = false;
}

The idea is very simple. First, we get colors data from graphics device, then we create a new Texture2D object and set colors data with saved colors data from graphics device. Finally, we call the SaveAsPng method to save current frame into an image file.

This entry was posted in XNA and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>