-
-
Save twobob/95843a3f1d3cf7e747bdeaf4f1def9fe to your computer and use it in GitHub Desktop.
Compress and decompress using SharpZipLib in Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.sebaslab.com/how-to-compress-and-decompress-binary-stream-in-unity/ | |
using ICSharpCode.SharpZipLib.BZip2; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using System.IO; | |
static void Compress (string nameOfTheFileToSave, ISerializable objectToSerialize) | |
{ | |
using (FileStream fs = new FileStream(nameOfTheFileToSave, FileMode.Create)) | |
{ | |
using (MemoryStream objectSerialization = new MemoryStream()) | |
{ | |
BinaryFormatter bformatter = new BinaryFormatter(); | |
bformatter.Serialize(objectSerialization, objectToSerialize); | |
using (BinaryWriter binaryWriter = new BinaryWriter(fs)) | |
{ | |
binaryWriter.Write(objectSerialization.GetBuffer().Length); //write the length first | |
using (BZip2OutputStream osBZip2 = new BZip2OutputStream(fs)) | |
{ | |
osBZip2.Write(objectSerialization.GetBuffer(), 0, objectSerialization.GetBuffer().Length); //write the compressed file | |
} | |
} | |
} | |
} | |
} | |
static void Decompress(string nameOfTheFileToLoad) | |
{ | |
using (FileStream fs = new FileStream(nameOfTheFileToLoad, FileMode.Open)) | |
{ | |
using (BinaryReader binaryReader = new BinaryReader(fs)) | |
{ | |
int length = binaryReader.ReadInt32(); //read the length first | |
byte[] bytesUncompressed = new byte[length]; //you can convert this back to the object using a MemoryStream ;) | |
using (BZip2InputStream osBZip2 = new BZip2InputStream(fs)) | |
{ | |
osBZip2.Read(bytesUncompressed, 0, length); //read the decompressed file | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment