uses zlib;

procedure CompOrUncomp(var Stream : TStream; Komp : Boolean);
var myStream : TMemorystream;

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;

begin 	
  myStream := TMemorystream.create;
  try
    if Komp then
      CompressStream(Stream, myStream)
    else
      DeCompressStream(Stream, myStream);
    stream.copyfrom(mystream, 0);
  finally
    FreeAndNil(mystream);
  end;
end;