「小さいファイルを gzip/deflate で圧縮すると末尾にゼロが多くなるのはなぜですか?」に対する答えがわかりません。」 (小さなファイルを gzip/deflate で圧縮すると、末尾のゼロが多くなるのはなぜですか? )
.NET 環境で ½ ~ 2 K バイトの少量のデータを最小サイズに圧縮するにはどうすればよいでしょうか? (ランタイムは私にとって問題ではありません。サイズと速度を交換できますか? サードパーティ製品を使用する必要がありますか? 開発者のライセンス料は問題ありませんが、ランタイム ライセンスは必要ありません。)
- 以下のコードを改善する方法について何か提案はあります
か? (a) より高い圧縮率?
(b) ストリームのより適切な使用?
改善が必要な 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;
}