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;


    return xnaTexture;