Compression and decompression problem with zlib.Ne

2020-02-29 09:07发布

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.

标签: c# .net zlib
2条回答
再贱就再见
2楼-- · 2020-02-29 09:40

longbkit, Thank you for that reference. There is code in there:

 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 diffrence 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.

❋ user "John Smith" broke original code since CopyTo doesn't work and raises exception in his edited text (And approved twice by others...). Reverting back to original code example by OP. Please test edited code next time before editing, thank you.

查看更多
家丑人穷心不美
3楼-- · 2020-02-29 09:52

Change code.

inZStream.Read

-> inZStream.read

from sourceCode in ZInputStream.cs

查看更多
登录 后发表回答