首页 > 解决方案 > 尝试保存 XNA Texture2D 时出错:System.Exception:“不支持纹理表面格式”

问题描述

我想将 a 保存Texture2D.png文件中。的表面格式Texture2D是 a SurfaceFormat.Dxt1,我相信这SaveAsPng就是抛出错误的原因System.Exception: 'Texture surface format not supported'

Stream stream = File.Create("file.png");
tex.SaveAsPng(stream, tex.Width, tex.Height);
stream.Dispose();

将 DxT1 格式保存为 png 的最佳方法是什么?

标签: c#graphicsxnapngtextures

解决方案


Texture2D.SaveAsPngMonoGame 中不支持 DXT 格式,但您可以通过 GPU 渲染并保存它。例如:

var gpu = texture.GraphicsDevice;
using (var target = new RenderTarget2D(gpu, texture.Width, texture.Height))
{
    gpu.SetRenderTarget(target);
    gpu.Clear(Color.Transparent); // set transparent background

    using (SpriteBatch batch = new SpriteBatch(gpu))
    {
        batch.Begin();
        batch.Draw(texture, Vector2.Zero, Color.White);
        batch.End();
    }

    // save texture
    using (Stream stream = File.Create("file.png"))
        target.SaveAsPng(stream, texture.Width, texture.Height);

    gpu.SetRenderTarget(null);
}

一些警告:

  • 这相对较慢,因此您可能希望使用Texture.SaveAsPng它支持的纹理格式。
  • 您不能在 XNA 绘制循环期间执行此操作,因为此时 GPU 将被占用。

推荐阅读