Is there a fast alternative to creating a Texture2D from a Bitmap object in XNA?

前端 未结 4 1695
终归单人心
终归单人心 2021-02-03 10:36

I\'ve looked around a lot and the only methods I\'ve found for creating a Texture2D from a Bitmap are:

using  (MemoryStream s = new  MemoryStream())
{
   bmp.Sav         


        
4条回答
  •  走了就别回头了
    2021-02-03 11:16

    they have changed the format from bgra to rgba in XNA 4.0, so that method gives strange colors, the red and blue channels needs to be switched. Here's a method i wrote that is super fast! (loads 1500x 256x256 pixel textures in about 3 seconds).

        private Texture2D GetTexture(GraphicsDevice dev, System.Drawing.Bitmap bmp)
        {
            int[] imgData = new int[bmp.Width * bmp.Height];
            Texture2D texture = new Texture2D(dev, bmp.Width, bmp.Height);
    
            unsafe
            {
                // lock bitmap
                System.Drawing.Imaging.BitmapData origdata = 
                    bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
    
                uint* byteData = (uint*)origdata.Scan0;
    
                // Switch bgra -> rgba
                for (int i = 0; i < imgData.Length; i++)
                {
                    byteData[i] = (byteData[i] & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);                        
                }                
    
                // copy data
                System.Runtime.InteropServices.Marshal.Copy(origdata.Scan0, imgData, 0, bmp.Width * bmp.Height);
    
                byteData = null;
    
                // unlock bitmap
                bmp.UnlockBits(origdata);
            }
    
            texture.SetData(imgData);
    
            return texture;
        }
    

提交回复
热议问题