How to achieve minimum size when compressing small amount of data lossless?

922 views Asked by At
  1. I don’t understand the answer to ”Why does gzip/deflate compressing a small file result in many trailing zeroes?” (Why does gzip/deflate compressing a small file result in many trailing zeroes?)

  2. How would you go about compressing small amount of data ½-2 Kbyte to minimum size in a .NET-environment? (Runtime is not an issue for me. Can I trade speed for size? Should I use 3rd party products? Developer license fees are OK, but runtime license not.)

  3. Any suggestions about how I can improve the code below for:
    (a) Higher compression ratio?
    (b) More proper use of streams?

Here is the C#-code that needs to be improved:

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

There are 0 answers