我的代码:
procedure CompressStream(var CompressedStream: TMemoryStream;const CompressionLevel: TCompressionLevel);
// CompressionLevel : (clNone, clFastest, clDefault, clMax);
var
SourceStream: TCompressionStream;
DestStream: TMemoryStream;
Count: int64;
begin
//获得流的原始尺寸
Count := CompressedStream.Size;
DestStream := TMemoryStream.Create;
SourceStream:=TCompressionStream.Create(CompressionLevel, DestStream);
Try
//SourceStream中保存着原始的流
CompressedStream.SaveToStream(SourceStream);
//将原始流进行压缩, DestStream中保存着压缩后的流
SourceStream.Free;
CompressedStream.Clear;
//写入原始流的尺寸
CompressedStream.WriteBuffer(Count, SizeOf(Count));
//写入经过压缩的流
CompressedStream.CopyFrom(DestStream, 0);
finally
DestStream.Free;
end;
end;
procedure UnCompressStream(const CompressedStream: TStream;
var UnCompressedStream: TMemoryStream);
var
SourceStream: TDecompressionStream;
DestStream: TMemoryStream;
Buffer: PChar;
Count: int64;
begin
//从被压缩的流中读出原始流的尺寸
CompressedStream.ReadBuffer(Count, SizeOf(Count));
//根据流尺寸大小为将要读入的原始流分配内存块
GetMem(Buffer, Count);
DestStream := TMemoryStream.Create;
SourceStream := TDecompressionStream.Create(CompressedStream);
Try
//将被压缩的流解压缩,然后存入 Buffer内存块中
SourceStream.ReadBuffer(Buffer^, Count);
//将原始流保存至 DestStream流中
DestStream.WriteBuffer(Buffer^, Count);
DestStream.Position := 0;//复位流指针
//从 DestStream流中载入原始流
UnCompressedStream.LoadFromStream(DestStream);
finally
FreeMem(Buffer);
DestStream.Free;
SourceStream.Free ;
end;
end;