压缩少量数据时如何实现最小尺寸无损?

时间:2011-03-03 12:51:01

标签: stream protocol-buffers gzipstream lossless-compression

  1. 我不明白“为什么gzip / deflate压缩小文件导致许多尾随零?”的答案 (Why does gzip/deflate compressing a small file result in many trailing zeroes?

  2. 如何在.NET环境中将少量数据½-2 Kbyte压缩到最小尺寸? (运行时对我来说不是问题。我可以换算速度吗?我应该使用第三方产品吗? 开发人员许可证费用没问题,但运行时许可证没有。)

  3. 有关如何改进以下代码的任何建议:
    (a)压缩比更高?
    (b)更恰当地使用溪流?
  4. 以下是需要改进的C#代码:

    private static byte[] SerializeAndCompress(MyClass myObject)  
    {
       using (var inStream = new System.IO.MemoryStream())
       {
    
         Serializer.Serialize< MyClass >(inStream, myObject); // PROTO-buffer  serialization. (Code not included here.)
         byte[] gZipBytearray = GZipCompress(inStream);
         return gZipBytearray;
       }
    }
    
    private static Byte[] GZipCompress(MemoryStream inStream)
    {
       inStream.Position = 0;
    
       byte[] byteArray;
       {
          using (MemoryStream outStream = new MemoryStream())
          {
             bool LeaveOutStreamOpen = true;
             using (GZipStream compressStream = new GZipStream(outStream, 
                CompressionMode.Compress, LeaveOutStreamOpen))
             {
             // Copy the input stream into the compression stream.
             // inStream.CopyTo(Compress); TODO: "Uncomment" this line and remove the next one after upgrade to .NET 4 or later.
                CopyFromStreamToStream(inStream, compressStream);
         }
         byteArray = CreateByteArrayFromStream(outStream); // outStream is complete first after compressStream have been closed.
          }
       }
       return byteArray;
    }
    
    private static void CopyFromStreamToStream(Stream sourceStream, Stream destinationStream)
    {
       byte[] buffer = new byte[4096];
       int numRead;
       while ((numRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
       {
         destinationStream.Write(buffer, 0, numRead);
       }
    }
    
    private static byte[] CreateByteArrayFromStream(MemoryStream outStream)
    {
       byte[] byteArray = new byte[outStream.Length];
       outStream.Position = 0;
       outStream.Read(byteArray, 0, (int)outStream.Length);
       return byteArray;
    }
    

0 个答案:

没有答案