HanDs
管理员

[Delphi文章] Zlib 流压缩解压 




procedure UnCompressionStream(var ASrcStream:TMemoryStream);  //解压缩
var
  nTmpStream:TDecompressionStream;
  nDestStream:TMemoryStream;
  nBuf: array[1..512] of Byte;
  nSrcCount: integer;
begin
  ASrcStream.Position := 0;
  nDestStream := TMemoryStream.Create;
  nTmpStream := TDecompressionStream.Create(ASrcStream);
  try
    repeat
      //读入实际大小
      nSrcCount := nTmpStream.Read(nBuf, SizeOf(nBuf));
      if nSrcCount > 0 then
        nDestStream.Write(nBuf, nSrcCount);
    until (nSrcCount = 0);
    ASrcStream.Clear;
    ASrcStream.LoadFromStream(nDestStream);
    ASrcStream.Position := 0;
  finally
    nDestStream.Clear;
    nDestStream.Free;
    nTmpStream.Free;
  end;
end;

procedure CompressionStream(var ASrcStream:TMemoryStream;ACompressionLevel:Integer = 2); //压缩流
var
  nDestStream:TMemoryStream;
  nTmpStream:TCompressionStream;
  nCompressionLevel:TCompressionLevel;
begin
  ASrcStream.Position := 0;
  nDestStream := TMemoryStream.Create;
  try
    //级别
    case ACompressionLevel of
      0:nCompressionLevel := clNone;
      1:nCompressionLevel := clFastest;
      2:nCompressionLevel := clDefault;
      3:nCompressionLevel := clMax;
      else
        nCompressionLevel := clMax;
    end;
    //开始压缩
    nTmpStream := TCompressionStream.Create(nCompressionLevel,nDestStream);
    try
      ASrcStream.SaveToStream(nTmpStream);
    finally
      nTmpStream.Free;//释放后nDestStream才会有数据
    end;
    ASrcStream.Clear;
    ASrcStream.LoadFromStream(nDestStream);
    ASrcStream.Position := 0;
  finally
    nDestStream.Clear;
    nDestStream.Free;
  end;
end;


学习中请遵守法律法规,本网站内容均来自于互联网,本网站不负担法律责任
Zlib 流压缩解压
#1楼
发帖时间:2016-7-9   |   查看数:0   |   回复数:0
游客组
快速回复