delphi 如何检查是否是GZip压缩算法?

kuarbcqp  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(198)

我有这样的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压缩?

41zrol4v

41zrol4v1#

C#代码检查GZip头,它是两个字节:

0x1f 0x8b

您可以在 Delphi 中执行相同的操作:

function IsGZipStream(Stream: TStream): Boolean;
var
  B1, B2: Byte;
begin
  Result := False;
  if Stream.Size >= 2 then
  begin
    Stream.Read(B1, 1);
    Stream.Read(B2, 1);
    Result := (B1 = $1F) and (B2 = $8B);
    Stream.Seek(-2, soFromCurrent);
  end;
end;

相关问题