public static class TextureLoader
{
public static Texture2D FromFile(GraphicsDevice device, string path, Microsoft.Xna.Framework.Rectangle? sourceRectangle = null)
{
// XNA 4.0 removed FromFile in favor of FromStream
// So if we don't pass a source rectangle just delegate to FromStream
if(sourceRectangle == null)
{
return Texture2D.FromStream(device, new FileStream(path, FileMode.Open));
}
else
{
// If we passed in a source rectangle convert it to System.Drawing.Rectangle
Microsoft.Xna.Framework.Rectangle xnaRectangle = sourceRectangle.Value;
System.Drawing.Rectangle gdiRectangle = new System.Drawing.Rectangle(xnaRectangle.X, xnaRectangle.Y, xnaRectangle.Width, xnaRectangle.Height);
// Start by loading the entire image
Image image = Image.FromFile(path);
// Create an empty bitmap to contain our crop
Bitmap bitmap = new Bitmap(gdiRectangle.Width, gdiRectangle.Height, image.PixelFormat);
// Draw the cropped image region to the bitmap
Graphics graphics = Graphics.FromImage(bitmap);
graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), gdiRectangle.X, gdiRectangle.Y, gdiRectangle.Width, gdiRectangle.Height, GraphicsUnit.Pixel);
// Save the bitmap into a memory stream
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);
// Finally create the Texture2D from stream
Texture2D texture = Texture2D.FromStream(device, stream);
// Clean up
stream.Dispose();
graphics.Dispose();
bitmap.Dispose();
image.Dispose();
return texture;
}
}
}