Serializing data is actually a pretty smart workaround, but XML is very hard to work with. I would do this using a custom-made, but simple binary format so you can control the size of the output.
Here are a few methods Iβve cracked that should work, but keep in mind that I specifically asked them to answer this question, and they have not been tested.
To save data.
private void SaveTextureData(Texture2D texture, string filename) { int width = texture.Width; int height = texture.Height; Color[] data = new Color[width * height]; texture.GetData<Color>(data, 0, data.Length); using (BinaryWriter writer = new BinaryWriter(File.Open(filename, FileMode.Create))) { 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); } } }
And download the data ..
private Texture2D LoadTextureData(string filename) { using (BinaryReader reader = new BinaryReader(File.Open(filename, FileMode.Open))) { 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(GraphicsDevice, width, height); texture.SetData<Color>(data, 0, data.Length); return texture; } }
Binary data is much smaller than XML data. This is about as small as you get without compression. Just keep in mind that binary formats are pretty tough when it comes to change. If you need to change the format, in most cases it will be easier to write new files.
If you need to make changes to methods, be careful to synchronize them. Each record must match an identical Read in the same order and data type.
I am interested to know how small the files are. Let me know how this happens?
source share