flibitijibibo/MonoGame — pull request #233 by nickgravelyn (2014-05-31 18:47:36+00:00)
Title: Extract extension method from core Texture2D.SaveAsPng method

To aid with screenshot taking I've moved the core logic of saving a texture to PNG into a public extension method. This makes taking screenshots nice:

int w = GraphicsDevice.PresentationParameters.BackBufferWidth;
int h = GraphicsDevice.PresentationParameters.BackBufferHeight;

// Get the back buffer contents
byte[] bbData = new byte[w * h * 4];
GraphicsDevice.GetBackBufferData(bbData);

// Set all alpha values to 255
for (int i = 3; i < bbData.Length; i += 4)
{
bbData[i] = 255;
}

// Save to file
using (var stream = File.Create("screenshot.png"))
{
Texture2D.TextureDataToPNGEXT(stream, bbData, w, h);
}

Without this extension, one has to get the back buffer, create a new texture, set the data on the texture (which pushes it to the GPU), then save the texture which pulls the data _back_ from the GPU to save it. That's all pretty silly and raises potential threading issues with OpenGL and the driver (if you wanted to save the screenshot on a background thread, for example).