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

前端 未结 4 1693
终归单人心
终归单人心 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:20

    You want LockBits? You get LockBits.

    In my implementation I passed in the GraphicsDevice from the caller so I could make this method generic and static.

    public static Texture2D GetTexture2DFromBitmap(GraphicsDevice device, Bitmap bitmap)
    {
        Texture2D tex = new Texture2D(device, bitmap.Width, bitmap.Height, 1, TextureUsage.None, SurfaceFormat.Color);
    
        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
    
        int bufferSize = data.Height * data.Stride;
    
        //create data buffer 
        byte[] bytes = new byte[bufferSize];    
    
        // copy bitmap data into buffer
        Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
    
        // copy our buffer to the texture
        tex.SetData(bytes);
    
        // unlock the bitmap data
        bitmap.UnlockBits(data);
    
        return tex;
    }
    

提交回复
热议问题