我有这样的C#代码,它能够验证MemoryStream
是否在解压缩前用GZip压缩:
// Ref: https://stackoverflow.com/a/6059342/16631852
if (input.ReadByte() == 0x1f && input.ReadByte() == 0x8b)
...
public MemoryStream Decompress(MemoryStream input)
{
MemoryStream wmfStream;
input.Position = 0;
if (input.ReadByte() == 0x1f && input.ReadByte() == 0x8b)
{
input.Position = 0;
wmfStream = new MemoryStream();
var buffer = new byte[1024];
var compressedFile = new GZipStream(input, CompressionMode.Decompress, true);
int bytesRead;
while ((bytesRead = compressedFile.Read(buffer, 0, buffer.Length)) > 0)
{
wmfStream.Write(buffer, 0, bytesRead);
}
}
else
{
wmfStream = input;
}
wmfStream.Position = 0;
return wmfStream;
}
后来,我发现了这段代码的一个可能的 Delphi 变体(在我看来),可以使用**System.Zlib
**进行GZip解压缩:
uses System.ZLib;
const
ZLIB_GZIP_WINDOWBITS = 31;
ZLIB_DEFLATE_WINDOWBITS = 15;
procedure ZLibDecompressStream(Source, Dest: TStream; const GZipFormat: Boolean = True); overload;
procedure ZLibDecompressStream(Source, Dest: TStream; const GZipFormat: Boolean);
var
WindowBits: Integer;
UnZip: TDecompressionStream;
begin
if GZipFormat then
WindowBits := ZLIB_GZIP_WINDOWBITS
else
WindowBits := ZLIB_DEFLATE_WINDOWBITS;
UnZip := TDecompressionStream.Create(Source, WindowBits);
try
Dest.CopyFrom(UnZip, 0);
finally
FreeAndNil(UnZip);
end;
end;
如何在初始化解压缩之前(类似于C#代码)验证(在 Delphi 代码中)MemoryStream
是否用GZip压缩?
1条答案
按热度按时间41zrol4v1#
C#代码检查GZip头,它是两个字节:
您可以在 Delphi 中执行相同的操作: