Compresser/décompresser un Stream

Uses
ZLib;

procedure CompressStream(inpStream, outStream: TStream);
var
InpBuf,OutBuf: Pointer;
InpBytes,OutBytes: integer;
begin
InpBuf := nil;
OutBuf := nil;
try
GetMem(InpBuf,inpStream.size);
inpStream.Position := 0;
InpBytes := inpStream.Read(InpBuf^,inpStream.size);
CompressBuf(InpBuf,InpBytes,OutBuf,OutBytes);
outStream.Write(OutBuf^,OutBytes);
finally
if InpBuf <> nil then FreeMem(InpBuf);
if OutBuf <> nil then FreeMem(OutBuf);
end;
end;

procedure DecompressStream(inpStream, outStream: TStream);
var
InpBuf,OutBuf: Pointer;
OutBytes,sz: integer;
begin
InpBuf := nil;
OutBuf := nil;
sz := inpStream.size-inpStream.Position;
if sz > 0 then try
GetMem(InpBuf,sz);
inpStream.Read(InpBuf^,sz);
DecompressBuf(InpBuf,sz,0,OutBuf,OutBytes);
outStream.Write(OutBuf^,OutBytes);
finally
if InpBuf <> nil then FreeMem(InpBuf);
if OutBuf <> nil then FreeMem(OutBuf);
end;
outStream.Position := 0;
end;


///exemple compression
procedure TForm1.Button1Click(Sender: TObject);
var
ms1, ms2 : TMemoryStream;
begin
ms1 := TMemoryStream.Create;
try
ms2 := TMemoryStream.Create;
try
RichEdit1.Lines.SaveToStream(ms1);
CompressStream(ms1,ms2);
ShowMessage(Format('Stream Compression Rate: %d %%',
[round(100 / ms1.Size * ms2.Size)]));
ms2.SaveToFile('C:ms2.dat');
finally
ms1.Free;
end;
finally
ms2.Free;
end;
end;

//exemple décompression
procedure TForm1.Button2Click(Sender: TObject);
var
ms1, ms2 : TMemoryStream;
begin
ms1 := TMemoryStream.Create;
try
ms2 := TMemoryStream.Create;
try
ms1.LoadFromFile('C:ms2.dat');
DecompressStream(ms1,ms2);
RichEdit1.Lines.LoadFromStream(ms2);
finally
ms1.Free;
end;
finally
ms2.Free;
end;
end;
Ajouter un commentaire
Pseudo
Adresse email
Site internet (optionnel)
Votre commentaire
Fiche de l'article
Mise a jour30/11/2001
VisualisationVu 993 fois
PublicInternaute zz
CategorieDelphi - Trucs et astuces - Systeme
Auteur de l'article
SwissDelphiCenter SwissDelphiCenter
connecté le 02/11/2011
329 articles dans la section
Contacter l'auteur