I am using ZLIB.Net and I just don't understand what should I do to compress a stream which is not FileStream
, but MemoryStream
. By doing:
byte[] buffer = ASCIIEncoding.ASCII.GetBytes("Hello World");
MemoryStream outStream = new MemoryStream();
zlib.ZOutputStream outZStream = new zlib.ZOutputStream(
outStream,
zlib.zlibConst.Z_BEST_COMPRESSION);
outZStream.Write(buffer, 0, buffer.Length);
outZStream.finish();
buffer = outStream.GetBuffer();
Debug.WriteLine(DateTime.Now.ToString() + ":" + buffer.Length);
MemoryStream inStream = new MemoryStream(buffer);
MemoryStream mo = new MemoryStream();
zlib.ZInputStream inZStream = new zlib.ZInputStream(
inStream,
zlib.zlibConst.Z_BEST_COMPRESSION);
int n = 0;
while ((n = inZStream.Read(buffer, 0, buffer.Length)) > 0)
{
mo.Write(buffer, 0, n);
}
string STR = ASCIIEncoding.ASCII.GetString(mo.GetBuffer());
I can't get the string "Hello World"
back.
Thanks to user @longbkit for the reference to the answer (itself by @JoshStribling) that helped me figure this out.
public static void CompressData(byte[] inData, out byte[] outData)
{
using (MemoryStream outMemoryStream = new MemoryStream())
using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_DEFAULT_COMPRESSION))
using (Stream inMemoryStream = new MemoryStream(inData))
{
CopyStream(inMemoryStream, outZStream);
outZStream.Finish();
outData = outMemoryStream.ToArray();
}
}
public static void DecompressData(byte[] inData, out byte[] outData)
{
using (MemoryStream outMemoryStream = new MemoryStream())
using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream))
using (Stream inMemoryStream = new MemoryStream(inData))
{
CopyStream(inMemoryStream, outZStream);
outZStream.Finish();
outData = outMemoryStream.ToArray();
}
}
public static void CopyStream(System.IO.Stream input, System.IO.Stream output)
{
byte[] buffer = new byte[2000];
int len;
while ((len = input.Read(buffer, 0, 2000)) > 0)
{
output.Write(buffer, 0, len);
}
output.Flush();
}
It works. But what I see is the only difference between Compression and Decompression is Compression Type in ZOutput Constructor...
Amazing. For me would be more clear if Compression is called Output while Decompression - Input. or such... in fact it's Output only.