XNA / Monogame Texture2D到字符串

时间:2015-08-04 17:37:56

标签: c# xml xna monogame texture2d

我想将一个小的png图像存储在XML文件中并将其加载回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();

1 个答案:

答案 0 :(得分:1)

直接来自你的字节数组create a MemoryStream,不需要用编写器填充它:

        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流。)