XNA / Monogame Texture2D 到字符串

XNA / Monogame Texture2D to to string

我想在 XML 文件中存储一个小的 png 图像并将其加载回 Texture2D。

这就是我正在做的

保存代码

我正在使用 BinaryWriter 将 Texture2D 的数据写入 MemoryStream,

然后将 MemoryStream 转换为数组。我必须将数组转换为 Base64String,因为您无法保存所有字符

在 XML 文件中。

字符串保存在我的 XML 文件中。

    public static string SaveTextureData(this Texture2D texture)
    {
        int width = texture.Width;
        int height = texture.Height;
        Color[] data = new Color[width * height];
        texture.GetData<Color>(data, 0, data.Length);

        MemoryStream streamOut = new MemoryStream();

        BinaryWriter writer = new BinaryWriter(streamOut);

           writer.Write(width);
            writer.Write(height);
            writer.Write(data.Length);

            for (int i = 0; i < data.Length; i++)
            {
                writer.Write(data[i].R);
                writer.Write(data[i].G);
                writer.Write(data[i].B);
                writer.Write(data[i].A);
            } 

        return Convert.ToBase64String(streamOut.ToArray());
    }

加载代码

这里也一样。我正在将 Base64Str 转换为数组并尝试读取它。

但是我读不回来

    public static Texture2D LoadTextureData(this string gfxdata, GraphicsDevice gfxdev)
    {
        byte[] arr = Convert.FromBase64String(gfxdata);

        MemoryStream input = new MemoryStream();

        BinaryWriter bw = new BinaryWriter(input);
        bw.Write(arr);

        using (BinaryReader reader = new BinaryReader(input))
        {
            var width = reader.ReadInt32();
            var height = reader.ReadInt32();
            var length = reader.ReadInt32();
            var data = new Color[length];

            for (int i = 0; i < data.Length; i++)
            {
                var r = reader.ReadByte();
                var g = reader.ReadByte();
                var b = reader.ReadByte();
                var a = reader.ReadByte();
                data[i] = new Color(r, g, b, a);
            }

            var texture = new Texture2D(gfxdev, width, height);
            texture.SetData<Color>(data, 0, data.Length);
            return texture;
        }
    }

这里可能需要一些帮助。

读取方法出现异常,无法读取值。 符合

var width = reader.ReadInt32();

只需 create a MemoryStream 直接来自您的字节数组,无需用 writer 填充它:

        byte[] arr = Convert.FromBase64String(gfxdata);

        using (var ms = new MemoryStream(arr))
        using (var reader = new BinaryReader(ms))
        {
            var width = reader.ReadInt32();
            var height = reader.ReadInt32();
            var length = reader.ReadInt32();
            var data = new Color[length];

            for (int i = 0; i < data.Length; i++)
            {
                var r = reader.ReadByte();
                var g = reader.ReadByte();
                var b = reader.ReadByte();
                var a = reader.ReadByte();
                data[i] = new Color(r, g, b, a);
            }

            // Allocate the Texture2D as before.
        }

(您的代码的具体问题是您在写入后没有倒带 input 流。)