如何用DELPHI的ZLIB来压缩?(20分)

  • 主题发起人 主题发起人 billrobin
  • 开始时间 开始时间
B

billrobin

Unregistered / Unconfirmed
GUEST, unregistred user!
如何用DELPHI的ZLIB来压缩?
 
压缩比较简单,但是需要你自己写个文件头来记录压缩文件的大小和其他信息如文件名等。
解压缩与此过程相反。
procedure ZipFile(SFileName, DFileName: string);
var
Zip: TCompressionStream;
SStream, DStream: TFileStream;
Size: Integer;
begin
try
Dstream := TFileStream.Create(DFileName,fmCreate);
except
ProcessError('无法创建文件 '+FFileName,-1,FCancel);
Exit;
end;
try
SStream := TFileSTream.Create(SFileName,fmOpenRead);
except
DStream.Free;
Exit;
end;
try
Zip := TCompressionStream.Create(FZipLevel,DStream);
except
DStream.Free;
SStream.Free;
Exit;
end;
try
Size := SSTream.Size;
Zip.WriteBuffer(Size, SizeOf(Size));//写文件大小,以便解压缩使用
Zip.CopyFrom(SSTream,SSTream.Size);
finally
Zip.Free;
SSTream.Free;
DStream.Free;
end;
 
我的代码:
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;
 
多人接受答案了。
 
后退
顶部