Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
356 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...