我正在使用 .NET 6 的
ZlibStream
来压缩数据。
我注意到当我压缩数据并立即解压缩时,原始数据和未压缩数据的大小是不同的。
我使用以下函数来压缩和解压缩:
public static class ZLib
{
public static byte[] CompressData(Stream inStream, CompressionLevel level = CompressionLevel.Optimal)
{
using (var outStream = new MemoryStream())
{
using (var compressStream = new ZLibStream(outStream, level, false) )
{
inStream.CopyTo(compressStream);
return outStream.ToArray();
}
}
}
public static byte[] DecompressData(Stream inStream)
{
using (var outStream = new MemoryStream())
{
using (var decompressStream = new ZLibStream(inStream, CompressionMode.Decompress))
{
decompressStream.CopyTo(outStream);
}
return outStream.ToArray();
}
}
public static byte[] CompressData(byte[] inData, CompressionLevel compressionLevel = CompressionLevel.Optimal)
{
using (var inStream = new MemoryStream(inData, false))
return CompressData(inStream, compressionLevel);
}
public static byte[] DecompressData(byte[] inData)
{
using (var inStream = new MemoryStream(inData, false))
return DecompressData(inStream);
}
}
用法如下:
private byte[] _texture32Data = ...;
//...//
byte[] texture32Compressed = ZLib.CompressData(_texture32Data, compressionLevel);
var texture32UncompressedSize = _texture32Data.Length;
var uncompressed = ZLib.DecompressData(texture32Compressed);
Debug.Assert(uncompressed.Length == texture32UncompressedSize); // Assert fires here
未压缩。长度= 10153463
纹理32未压缩大小= 10223616
我在这里做错了什么?
编辑:
背景:
我目前正在重构我们的 MiniZ 依赖项。当我使用 MiniZ 时,尺寸是正确的。
您遇到的问题是由于 .NET 6 中的已知更改所致,如此处所述。
为了解决您的问题:
public static byte[] DecompressData(Stream inStream)
{
byte[] buffer = new byte[4096];
int bytesRead;
using (var outStream = new MemoryStream())
{
using (var decompressStream = new ZLibStream(inStream, CompressionMode.Decompress))
{
while ((bytesRead = decompressStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
}
return outStream.ToArray();
}
}
}