2

XNA.Texture2D to System.Drawing.Bitmap I am sure this answered my question but it linked an external site and is no longer available.

I am using a windows form in an xna game. I want to use a background image for one of my panels. It is easy enough to do the loading from file, but when the game is deployed to another system obviously the file location will be different.

Bitmap bmp = new Bitmap(@"c:\myImage.png");

In the above mentioned question, someone had suggested usign Texture2d.saveToPng then open the bitmap from the memory stream. This sounds great, if someone could steer me in that direction. Any other ideas?

Community
  • 1
  • 1
General Grey
  • 3,598
  • 2
  • 25
  • 32

2 Answers2

6

This works for me. If there are problems with it please let me know.

public static Image Texture2Image(Texture2D texture)
{
   Image img;
   using (MemoryStream MS = new MemoryStream())
   {
       texture.SaveAsPng(MS, texture.Width, texture.Height);
       //Go To the  beginning of the stream.
       MS.Seek(0, SeekOrigin.Begin);
       //Create the image based on the stream.
       img = Bitmap.FromStream(MS);
   }
   return img;
}
Omar
  • 16,329
  • 10
  • 48
  • 66
General Grey
  • 3,598
  • 2
  • 25
  • 32
  • 1
    I am just as happy to give you credit for yours, though you have a few typo's (bmp.Width should be texture.Width etc...) and some guys here will slam you for not including the using with the memorystream. – General Grey Sep 19 '12 at 13:43
  • Yeah I mean texture. Although I used `System.Drawing.Bitmap` instead of `using System.Drawing;` because else it won't compile due to the fact that `Microsoft.Xna.Framework;` contains some classes with the same name, for example `Color` class. – Omar Sep 19 '12 at 13:57
1

You can use two methods that allow you to create a Bitmap, use Texture2D.SaveAsJpeg() or Texture2D.SaveAsPng().

MemoryStream memoryStream = new MemoryStream();
Texture2D texture = Content.Load<Texture2D>( "Images\\test" );
texture.SaveAsJpeg( memoryStream, texture.Width, texture.Height ); //Or SaveAsPng( memoryStream, texture.Width, texture.Height )

System.Drawing.Bitmap bmp = new System.Drawing.Bitmap( memoryStream );
Omar
  • 16,329
  • 10
  • 48
  • 66