Delphi 使用 ZLib 压缩和解压 GZip
作者:互联网
ZLib是DEFLATE算法的实现库,它的API同时支持gzip文件格式以及一个简化的数据流格式。zlib数据流格式、DEFLATE以及gzip文件格式均已被分别标准化为 RFC 1950、RFC 1951、RFC 1952。
gzip在 HTTP压缩,一种在万维网中加速传输HTML和其他内容的技术。它是在 RFC 2016 中规定的三种标准HTTP压缩格式之一。这个RFC页定义了一种叫做"DEFLATE"的zlib格式,它和gzip格式相同,除了gzip添加了11字节头部和尾部的负载。但是,现在还是建议使用gzip而不是zlib,因为根据 RFC 1950, IE还没有正确的实现该标准,还不能处理zlib格式。
Delphi 使用 ZLib 压缩和解压 GZip:
uses System.ZLib; const ZLIB_GZIP_WINDOWBITS = 31; ZLIB_DEFLATE_WINDOWBITS = 15; type TZLibCompressionLevel = TZCompressionLevel; /// <summary> /// 使用 ZLib 压缩流 /// </summary> /// <param name="Source">要压缩的数据流</param> /// <param name="Dest">压缩后的数据流</param> /// <param name="Level">压缩级别</param> /// <param name="GZipFormat">是否使用 GZip 压缩算法</param> procedure ZLibCompressStream(Source, Dest: TStream; const Level: TZLibCompressionLevel = zcFastest; const GZipFormat: Boolean = True); overload; /// <summary> /// 使用 ZLib 解压缩流 /// </summary> /// <param name="Source">要解压的数据流</param> /// <param name="Dest">解压后的数据流</param> /// <param name="GZipFormat">是否使用 GZip 压缩算法</param> procedure ZLibDecompressStream(Source, Dest: TStream; const GZipFormat: Boolean = True); overload; procedure ZLibCompressStream(Source, Dest: TStream; const Level: TZLibCompressionLevel; const GZipFormat: Boolean); var WindowBits: Integer; Zip: TZCompressionStream; begin if GZipFormat then WindowBits := ZLIB_GZIP_WINDOWBITS else WindowBits := ZLIB_DEFLATE_WINDOWBITS; Zip := TZCompressionStream.Create(Dest, Level, WindowBits); try Zip.CopyFrom(Source, 0); finally FreeAndNil(Zip); end; end; 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;
标签:const,GZipFormat,Delphi,ZLib,DEFLATE,RFC,WindowBits,GZip,WINDOWBITS 来源: https://www.cnblogs.com/rtcmw/p/12863055.html