Converting Windows Bitmaps to XNA
Friday, December 5, 2008 at 08:33PM If you have ever wondered how to convert Windows Bitmaps into XNA textures then wonder no more. This method will do it for you. It is not particularly elegant (or fast) but it will let you take images off your PC (or the web) and put them into textures for use in XNA programs. Note that this will only work on XNA programs that are running on a Windows PC, the Xbox is not allowed to do this kind of thing at all. You need to add a reference to System.Drawing to your project and use the System.Drawing namespace.
Some of the code is a bit messy because of namespace clashes, and I'm sure there is a neater way of doing this. But it does work.
private Texture2D XNATextureFromBitmap(
System.Drawing.Bitmap b, GraphicsDevice device)
{
Texture2D xnaTexture =
new Texture2D(device, b.Width, b.Height);
Microsoft.Xna.Framework.Graphics.Color[] dots =
new Microsoft.Xna.Framework.Graphics.Color
[b.Width * b.Height];
int x;
int y;
int pos = 0;
for (y = 0; y < b.Height; y++)
{
for (x = 0; x < b.Width; x++)
{
System.Drawing.Color sourceColor = b.GetPixel(x, y);
dots[pos].A = 0xff;
dots[pos].R = sourceColor.R;
dots[pos].G = sourceColor.G;
dots[pos].B = sourceColor.B;
pos++;
}
}
xnaTexture.
SetData<Microsoft.Xna.Framework.Graphics.Color>(dots);
return xnaTexture;
}
Rob |
9 Comments |
XNA
Reader Comments (9)
Anyhoot, is this an on-the-fly type solution? Meaning, I have a bitmap image, want to load it in XNA as a Texture2D, I would need this? XNA does not support bitmaps? I think I am a bit confused...
One other question then, would this, or should I say could this, be considered a "content importer" extension?
Thanks for any more insight!
Shawn
I just hope, ney pray that you find my code perfectly readable should you assess my work.
public static Texture2D BitmapToTexture2D(System.Drawing.Bitmap bitmap, GraphicsDeviceManager graphics)
{
Texture2D texture;
using (MemoryStream s = new MemoryStream())
{
bitmap.Save(s, System.Drawing.Imaging.ImageFormat.Bmp);
s.Seek(0, SeekOrigin.Begin);
texture = Texture2D.FromFile(graphics.GraphicsDevice, s);
}
return texture;
}
http://www.codeproject.com/KB/game/VidTextureClassWebcamApp.aspx
Basically the camera input uses a DirectShow library. Unfortunately the sample here is quite old so may require a bit of re-jigging to get working with newer versions of XNA - there should be some help with this in the comments section of the page.
Change: dots[pos].A = 0xff;
To: dots[pos].A = sourceColor.A;
Alpha transparency on the source Bitmap is preserved, which comes in handy if you're doing what I did - using Image's up until the script, then doing a 'new Bitmap(Image)' - now it goes in with alpha, and comes out with it too!
Other than that though, the script saved me my hair - I was almost to the point of yanking it out trying to convert Image/Bitmap to Texture2D. Thanks much!