Thought for the Dazed

I've had to give up that Distance Learning course as I was having trouble seeing the teacher.

Flickr
www.flickr.com
RobMiles' items Go to RobMiles' photostream
Twitter
C# Yellow Book

Search entire site
« Zombie Fragfest | Main | Departmental Christmas Bash »
Friday
Dec052008

Converting Windows Bitmaps to XNA

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;
}

Reader Comments (9)

Ok, I am going to post a VerySillyQuestion!! Ha, you like that right, a little play on words...:/

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
December 8, 2008 | Unregistered CommenterShawn
Yep. If you have a Windows Bitmap such as the ones that you get from image files, or by download from the net, this method will convert the bitmap into a Texture which you can use in your XNA program. I wrote it because I'm upgrading my XNA RSS feed display program so that it can download and display images from feeds.
December 8, 2008 | Registered CommenterRob
You were right, your code is definately readable.

I just hope, ney pray that you find my code perfectly readable should you assess my work.
December 9, 2008 | Unregistered CommenterJDog - Joel Parkey
I've been doing a lot of work recently with a game which uses webcam input and, as such, have needed a fast method of converting Bitmap to Texture. Rather than cycling through each pixel, I simply saved the bitmap to memory and reloaded it into the content manager. This runs extremely smoothly in real-time, despite being called for every camera frame received:

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;
}
December 9, 2008 | Unregistered CommenterBurkey
Webcam input...interesting, care to elaborate Burkey?
December 9, 2008 | Unregistered CommenterShawn
Oooh. I never thought of that. What a neat (and fast) way of doing it. And coupling a webcam to an XNA game on the PC. That is such a great idea. If you have any code around I'd love to see it.
December 9, 2008 | Registered CommenterRob
There's a good sample linked below which could help get you going, my code is a bit of a mess at the moment (but will be tidied up in the future and hopefully I can stick it up on my blog, depending on IP rights from my university - d'oh!).

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.
December 9, 2008 | Unregistered CommenterBurkey
Couldn't you just find a nice program to convert windows bitmaps to .png files and load them as a normal 2dtexture.
December 10, 2008 | Unregistered CommenterNC
I found a change that might come in handy for other devs who are making images with transparency on the fly; I noticed the loss of alpha when using this script.

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!
January 12, 2009 | Unregistered CommenterLivewire

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.