zlib的减压(ZLib decompression)

2019-08-02 10:54发布

我想压缩使用zlib NET库数据。 不管未压缩字符串的内容我只似乎得到两个字节的数据在原始[]。

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    Stream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public 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();
}

Answer 1:

这里的问题是,实际上ZOutputStream写一些信息添加到完成()方法的流(这是由关闭调用)。 Close方法也关闭基本流,所以这不是在这种情况下多大用处。

代码更改为下面应该工作:

{
    string uncompressed = "1234567890";
    byte[] data = UTF8Encoding.Default.GetBytes(uncompressed);

    MemoryStream input = new MemoryStream(data);
    MemoryStream output = new MemoryStream();
    ZOutputStream outZStream = new ZOutputStream(output,zlibConst.Z_DEFAULT_COMPRESSION);

    CopyStream(input, outZStream);

    outZStream.finish();

    output.Seek(0, SeekOrigin.Begin);
    byte[] raw = output.ToArray();
    string compressed = Convert.ToBase64String(raw);
}

public 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();
}


文章来源: ZLib decompression