ZLib decompression

前端 未结 1 1142
忘了有多久
忘了有多久 2021-01-24 10:24

I am trying to compress data using the zlib .net library. Regardless of the content of the uncompressed string I only seem to get two bytes of data in the raw[].



        
相关标签:
1条回答
  • 2021-01-24 11:08

    The problem here is that the ZOutputStream actually writes some of the information into the stream in the finish() method (which is called by Close). The Close method also closes the base stream, so that is not much use in this situation.

    Changing the code to the following should work:

    {
        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();
    }
    
    0 讨论(0)
提交回复
热议问题