Skip to content

Instantly share code, notes, and snippets.

@unity3dcollege
Created July 22, 2017 21:31
Show Gist options
  • Save unity3dcollege/4dd9352b79a81595c7d0f58fa318e48e to your computer and use it in GitHub Desktop.
Save unity3dcollege/4dd9352b79a81595c7d0f58fa318e48e to your computer and use it in GitHub Desktop.
using System.IO;
using System.IO.Compression;
public static class ByteArrayExtensions
{
public static byte[] Compress(this byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory,CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
public static byte[] Decompress(this byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment