In this post I will present 2 little methods used on converting from a System.Drawing.Image to a Microsoft.Xna.Graphics.Texture2D and back again.
To convert a Texture2D to an Image :
public static System.Drawing.Image Texture2Image(Texture2D texture)
{
if (texture == null)
{
return null;
}
if (texture.IsDisposed)
{
return null;
}
//Memory stream to store the bitmap data.
MemoryStream ms = new MemoryStream();
//Save the texture to the stream.
texture.SaveAsPng(ms, texture.Width, texture.Height);
//Seek the beginning of the stream.
ms.Seek(0, SeekOrigin.Begin);
//Create an image from a stream.
System.Drawing.Image bmp2 = System.Drawing.Bitmap.FromStream(ms);
//Close the stream, we nolonger need it.
ms.Close();
ms = null;
return bmp2;
}
To convert an Image to a Texture2D:
public static void Image2Texture(System.Drawing.Image image,
GraphicsDevice graphics,
ref Texture2D texture)
{
GraphicsDevice graphics,
ref Texture2D texture)
{
if (image == null)
{
return;
}
if (texture == null || texture.IsDisposed ||
texture.Width != image.Width ||
texture.Height != image.Height ||
texture.Format != SurfaceFormat.Color)
{
if (texture != null && !texture.IsDisposed)
{
texture.Dispose();
}
texture = new Texture2D(graphics,image.Width,image.Height,false,SurfaceFormat.Color);
}
else
{
for (int i = 0; i < 16; i++)
{
if (graphics.Textures[i] == texture)
{
graphics.Textures[i] = null;
break;
}
}
}
//Memory stream to store the bitmap data.
MemoryStream ms = new MemoryStream();
//Save to that memory stream.
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//Go to the beginning of the memory stream.
ms.Seek(0, SeekOrigin.Begin);
//Fill the texture.
texture = Texture2D.FromStream(graphics, ms, image.Width, image.Height, false);
//Close the stream.
ms.Close();
ms = null;
}
This methods can be handy when you are building an editor that is using both XNA and WindowsForms(GDI+)
Here is a link, it's on SkyDrive so if you have an account and you are not logged in you might not see it :
Image2Texture2D
This is exactly what I needed for my level editor, thanks!
ReplyDeleteThanks for sharing these functions. In Image2Texture when calling Texture2D.FromStream you are referencing the graphics device as a property instead of through the parameter that was passed into the function. To avoid this problem I'd suggest making the functions static.
ReplyDeleteThanks for notifying me about that, it was an error,I meant to use the same reference that I was passing as a parameter to the function.
ReplyDeleteFixed the problem.
Thank you, I've been having problems of loading pictures into a Texture2D.FromStream directly but I don't know why it keeps going into an "An unexpected error has occurred."
ReplyDeletebut using Image.FromFile then using this method to convert into a texture2D works perfectly !
Thank you again.