是否有一种快速替代方法可以从 XNA 中的位图对象创建 Texture2D?

2024-05-03

我环顾四周,发现从位图创建Texture2D的唯一方法是:

using  (MemoryStream s = new  MemoryStream())
{
   bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png);
   s.Seek(0, SeekOrigin.Begin);
   Texture2D tx = Texture2D.FromFile(device, s);
}

and

Texture2D tx = new Texture2D(device, bmp.Width, bmp.Height,
                        0, TextureUsage.None, SurfaceFormat.Color);
tx.SetData<byte>(rgbValues, 0, rgbValues.Length, SetDataOptions.NoOverwrite);

其中 rgbValues 是一个字节数组,包含 32 位 ARGB 格式的位图像素数据。

我的问题是,我可以尝试更快的方法吗?

我正在编写一个地图编辑器,它必须读取自定义格式的图像(地图图块)并将其转换为要显示的Texture2D 纹理。编辑器的早期版本是 C++ 实现,它首先将图像转换为位图,然后转换为要使用 DirectX 绘制的纹理。我在这里尝试了相同的方法,但是上述两种方法都太慢了。在合理规格的计算机上,将地图所需的所有纹理加载到内存中,第一种方法大约需要 250 秒,第二种方法大约需要 110 秒(作为比较,C++ 代码大约需要 5 秒)。如果有一种方法可以直接编辑纹理数据(例如使用 Bitmap 类的 LockBits 方法),那么我将能够将自定义格式图像直接转换为 Texture2D,并有望节省处理时间。

任何帮助将非常感激。

Thanks


你想要 LockBits 吗?你会得到LockBits。

在我的实现中,我从调用者传入了 GraphicsDevice,这样我就可以使该方法通用且静态。

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有一种快速替代方法可以从 XNA 中的位图对象创建 Texture2D? 的相关文章

随机推荐